VB.NET 计算要使用 WebClient 复制的文件数

VB.NET Count number of files to copy with WebClient

我正在尝试编写一个代码,将文件从一个文件夹复制到另一个文件夹,带有进度条和 Label 来计算文件数量,例如 Copying 0 files of 10 files。但我的代码无法正常工作并抛出错误。

Collection was modified; enumeration operation may not execute.

这是我的代码:

Imports System.IO
Imports System.Net
Public Class Form1

Dim filesToCopy As New ArrayList()
Protected Overrides Sub OnLoad(ByVal e As EventArgs)
    MyBase.OnLoad(e)
    CopyBtn.Text = "Copy File"
    CopyBtn.Parent = Me
    ProgBar.Left = CopyBtn.Right
End Sub
Dim WithEvents CopyBtn As New Button
Dim ProgBar As New ProgressBar
Dim WithEvents FileCopier As New WebClient
Public Sub check(ByVal sender As Object, ByVal e As EventArgs) Handles CopyBtn.Click

    Dim src As String = "D:\test"
    Dim dest As String = "D:\test2"

    For Each Dir As String In System.IO.Directory.GetFiles(src)
        Dim dirInfo As New System.IO.DirectoryInfo(Dir)
        If Not System.IO.File.Exists(dest & "\" & dirInfo.Name) Then
            filesToCopy.Add(dirInfo.Name)
        End If
    Next

    If filesToCopy.Count > 0 Then
        If MsgBox("There are new files found. Do you want to sync it now?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm") = MsgBoxResult.Yes Then
            For i = 0 To filesToCopy.Count - 1
                Dim FileCopier As WebClient = New WebClient
                AddHandler FileCopier.DownloadProgressChanged, AddressOf FileCopier_DownloadProgressChanged
                AddHandler FileCopier.DownloadFileCompleted, AddressOf FileCopier_DownloadFileCompleted

                CopyBtn.Enabled = False
                ProgBar.Parent = Me
                FileCopier.DownloadFileAsync(New Uri(src & "\" & filesToCopy(i)), dest & "\" & filesToCopy(i))

            Next
        End If
    Else
        MsgBox("No new files to be copied")
    End If
End Sub

这是我跟踪文件复制数量的代码。

Private Sub FileCopier_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) Handles FileCopier.DownloadProgressChanged
    ProgBar.Value = e.ProgressPercentage

    For Each file In filesToCopy
        total += filesToCopy.Add(file)
    Next

    Label2.Text = total \ filesToCopy.Count
End Sub
End Class

将其添加到此处而不是 DownloadProgressChanged

   For i = 0 To filesToCopy.Count - 1
            Dim FileCopier As WebClient = New WebClient
            AddHandler FileCopier.DownloadProgressChanged, AddressOf FileCopier_DownloadProgressChanged
            AddHandler FileCopier.DownloadFileCompleted, AddressOf FileCopier_DownloadFileCompleted

        CopyBtn.Enabled = False
        ProgBar.Parent = Me
        FileCopier.DownloadFileAsync(New Uri(src & "\" & filesToCopy(i)), dest & "\" & filesToCopy(i))
        Label2.Text = i + 1 & "/" & FilesToCopy.Count 'PUT IT HERE INSTEAD

    Next