复制文件夹VB.NET时平滑进度条

时间:2016-02-02 08:54:43

标签: .net vb.net loops directory progress-bar

我正在创建一个将子文件夹复制到另一个文件夹的程序,而我的进度条效果不好,就像我复制单个子文件夹时它的百分比只有20%并停在那里,但是如果它的2个子文件夹停止在50%,它的加载进度就像是一个不顺畅的捷径。

你能帮帮我们吗?

更新

这是我的代码:

Dim foldersToCopy As New ArrayList()

Sub CopyFolders()

Dim foldsrc As DirectoryInfo = New DirectoryInfo(src)

    For Each folders In foldsrc.GetDirectories
        If Not System.IO.Directory.Exists(dest & "\" & folders.Name) Then
            foldersToCopy.Add(folders.Name)
        End If
    Next

    Dim src As String = Form2.TextBox1.Text
    Dim dest As String = Form2.TextBox2.Text

    Dim fcount = Directory.GetDirectories(src).Length
    Dim ftransfer As Integer = 0
    For i = 0 To foldersToCopy.Count - 1
            My.Computer.FileSystem.CopyDirectory(src & "\" & foldersToCopy(i), dest & "\" & foldersToCopy(i), True)
            ftransfer += 1
            Pbar1.value += ftransfer * 50 / fcount
            Pbar1.Update()
    Next
End Sub

和顺便说一下,我可以使用WebClient e.ProgressPercentageDownloadProgressChanged来获取此代码以获得顺畅的进度条吗? =)

2 个答案:

答案 0 :(得分:0)

ProgressBar值从0到100(%),因此您必须缩放循环中的数字以计算出已完成的百分比:

For i = 0 To foldersToCopy.Count - 1
    'copy the folder here
    Dim percentage = CSng(100 / foldersToCopy.Count * (i + 1))
    Pbar1.value = percentage
Next

答案 1 :(得分:0)

确定一些变化。我已将您的folderstocopy声明移动到sub中。 还添加了一行来将Pbar1.maximum设置为要复制的文件夹数减一,这样循环的最后一个循环,进度条将在最后,你不必乱七八糟地重新计算如何获得0到0之间的值100.还

Sub CopyFolders()

Dim foldersToCopy As New ArrayList()
Dim foldsrc As DirectoryInfo = New DirectoryInfo(src)

    For Each folders In foldsrc.GetDirectories
        If Not System.IO.Directory.Exists(dest & "\" & folders.Name) Then
            foldersToCopy.Add(folders.Name)
        End If
    Next

    Dim src As String = Form2.TextBox1.Text
    Dim dest As String = Form2.TextBox2.Text

    Dim fcount = Directory.GetDirectories(src).Length
    Dim ftransfer As Integer = 0
    Pbar1.Maximum=fcount
    For i = 0 To foldersToCopy.Count - 1
            My.Computer.FileSystem.CopyDirectory(src & "\" & foldersToCopy(i), dest & "\" & foldersToCopy(i), True)
            Pbar1.value += 1
            Pbar1.Update()
    Next
End Sub

让我知道