如何在vb.net复制从一个文件夹的文件到另一个期间设置进度条?(how to set progre

2019-08-18 02:02发布

目前我正在做在vb.net的项目,我想设置的进度条,同时从一个文件夹复制到另一个文件。 和进度条应努力完成根据复制文件的数量移动。

Answer 1:

概念应用于 :获取count of filessource directory ,然后只要copying一个filesource folderdestination folder增加一个variable来跟踪多少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


Answer 2:

事实并非如此新的问题,但这里仍然一个答案。 下面的代码将获得期望的结果,由此一个单独的文件的进度被跟踪。 它采用了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()


文章来源: how to set progress bar during copying file from one folder to another in vb.net?