【问题标题】:how to set progress bar during copying file from one folder to another in vb.net?如何在 vb.net 中将文件从一个文件夹复制到另一个文件夹时设置进度条?
【发布时间】:2013-03-28 06:26:03
【问题描述】:

目前我正在 vb.net 中做项目,我想在将文件从一个文件夹复制到另一个文件夹时设置进度条。并且进度条应根据复制的文件量向完成移动。

【问题讨论】:

  • 对于寻求解决方案的读者的注意事项,其中单个进度指示器 PER FILE 就足够了:My.Computer.FileSystem.CopyFile(OldLocation, NewLocation, FileIO.UIOption.AllDialogs) 将显示标准的 Windows 复制显示。

标签: vb.net copy progress-bar


【解决方案1】:

不是那么新的问题,但这里有一个答案。以下代码将达到预期的结果,从而跟踪单个文件的进度。它使用 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()

【讨论】:

  • 这太棒了!是否有可能获得传输字节标签的实时输出?谢谢!
  • @SilverSlash,完全有可能。由于此解决方案使用 1 MiB 缓冲区,因此它会精确到最接近的 MiB。就像streamRead.Position用来计算进度条值一样,可以用来显示已经处理的字节数。
  • 我该怎么做呢?我将字节缓冲区更改为(4096)。谢谢。
  • 假设您有一个名为lblBytesRead 的标签,您只需在Application.DoEvents() 之前添加lblBytesRead.Text = streamRead.Position
【解决方案2】:

使用的概念:在source directory 中获取count of files,然后每当copyingfilesource 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

【讨论】:

  • 我目前正在使用这个东西,但是当大文件到来时,它看起来像挂起,所以我尝试让进度条处理所有选定文件的总大小,比如总大小为 5文件是 100MB,然后当 50MB 完成时,无论传输多少文件,进度条都应该是一半。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-22
  • 2014-02-10
  • 2020-07-30
  • 2017-02-11
  • 1970-01-01
  • 2023-01-14
相关资源
最近更新 更多