如何在 vb.net 中将文件从一个文件夹复制到另一个文件夹时设置进度条? [英] how to set progress bar during copying file from one folder to another in vb.net?
问题描述
目前我正在 vb.net 中做项目,我想在将文件从一个文件夹复制到另一个文件夹时设置进度条.并且进度条应根据复制的文件量向完成移动.
Currently I'm doing project in vb.net and I want to set the progress bar while copying files from one folder to another. And the progress bar should move towards completion according to amount of file copied.
推荐答案
不是那么新的问题,但这里有一个答案.以下代码将达到预期的结果,从而跟踪单个文件的进度.它使用 1 MiB 缓冲区.根据您的系统资源,您可以相应地调整缓冲区以调整传输性能.
Not so new question, but here's an answer nonetheless. The following code will achieve the desired result whereby an individual file's progress is tracked. It uses a 1 MiB buffer. Depending on your system's resources, you can adjust the buffer accordingly to tweak the performance of the transfer.
概念:计算读取/写入的每个字节,并使用文件流根据源文件的总大小报告进度.
Concept: Count each byte as it is read/written and report the progress based on the total size of the source file, using file streams.
'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()
这篇关于如何在 vb.net 中将文件从一个文件夹复制到另一个文件夹时设置进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!