目前我正在 vb.net 中做项目,我想在将文件从一个文件夹复制到另一个文件夹时设置进度条。并且进度条应根据复制的文件量向完成移动。
问问题
17559 次
2 回答
3
不是那么新的问题,但这里有一个答案。以下代码将达到预期的结果,从而跟踪单个文件的进度。它使用 1 MiB 缓冲区。根据您的系统资源,您可以相应地调整缓冲区以调整传输性能。
概念:在读取/写入每个字节时对其进行计数,并使用文件流根据源文件的总大小报告进度。
'Create the file stream for the source file
Dim streamRead as New System.IO.FileStream([sourceFile], System.IO.FileMode.Open)
'Create the file stream for the destination file
Dim streamWrite as New System.IO.FileStream([targetFile], System.IO.FileMode.Create)
'Determine the size in bytes of the source file (-1 as our position starts at 0)
Dim lngLen as Long = streamRead.Length - 1
Dim byteBuffer(1048576) as Byte 'our stream buffer
Dim intBytesRead as Integer 'number of bytes read
While streamRead.Position < lngLen 'keep streaming until EOF
'Read from the Source
intBytesRead = (streamRead.Read(byteBuffer, 0, 1048576))
'Write to the Target
streamWrite.Write(byteBuffer, 0, intBytesRead)
'Display the progress
ProgressBar1.Value = CInt(streamRead.Position / lngLen * 100)
Application.DoEvents() 'do it
End While
'Clean up
streamWrite.Flush()
streamWrite.Close()
streamRead.Close()
于 2016-01-22T04:50:51.680 回答
2
使用的概念:在 中获取count of files
,source directory
然后每当copying
afile
从source folder
增加destination folder
avariable
以跟踪转移了多少files
。现在files
使用以下公式计算转移百分比,
% of files transferred = How many files Transferred * 100 / Total No of files in source folder
然后在获得 之后% of files transferred
,使用它来更新进度条的值。
试试这个代码:Tested with IDE
Dim xNewLocataion = "E:\Test1"
Dim xFilesCount = Directory.GetFiles("E:\Test").Length
Dim xFilesTransferred As Integer = 0
For Each xFiles In Directory.GetFiles("E:\Test")
File.Copy(xFiles, xNewLocataion & "\" & Path.GetFileName(xFiles), True)
xFilesTransferred += 1
ProgressBar1.Value = xFilesTransferred * 100 / xFilesCount
ProgressBar1.Update()
Next
于 2013-03-28T07:10:05.607 回答