【发布时间】:2016-03-27 09:08:53
【问题描述】:
我正在创建一个具有自动备份功能的程序,当我尝试将大文件或多个文件复制到单个文件夹中时,我的应用程序变得无响应/无响应。
我正在使用 System.IO.File.Copy(源、目标)来复制文件。
下面是我复制文件的代码。我还使用进度条来指示文件复制过程。
Imports System.IO
Public class Form1
Private Sub btnDestPath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowseDestPath.Click
'get destination path from FolderBrowserDialog
Dim destination As String
If (FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
destination = FolderBrowserDialog1.SelectedPath
txtDestination.Text = destination
End If
End Sub
Private Sub btnCopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCopy.Click
'set folder to copy files
Dim sourceFilePath As String = "C:\copyfiles\"
'get destinationpath from txtDestination.Text label
Dim destinationPath As String = txtDestination.Text.Replace(vbCrLf, "")
'add back slash(\) to destinationPath
Dim filepath As String = destinationPath & "\"
'count number of files to copy
Dim filecount As String
filecount = Directory.GetFiles(sourceFilePath).Count
ProgressBar1.Maximum = 1
ProgressBar1.Maximum = filecount 'represent the # of files
ProgressBar1.Step = 1 'step property value of 1 to represent each file being copied
For Each filename As String In Directory.GetFiles(sourceFilePath)
'check if files exist or not
If File.Exists(filename) Then
Dim dFile As String = String.Empty
Dim dFilePath As String = String.Empty
dFile = Path.GetFileName(filename) 'source file filenames
dFilePath = filepath & dFile 'concatenate filepath and filenames
File.Copy(filename, dFilePath, True) 'copy files from "c:\copyfiles" folder to destinationPath
ProgressBar1.PerformStep()
End If
Next
MsgBox("Copy Successful", vbOKOnly, "Message")
End Sub
End Class
我可以做些什么来改进代码。我听说使用 BackgroundWorker 可以解决问题,但我不知道从哪里开始。我只是 .NET 语言的新手。
任何帮助都会很棒。
【问题讨论】: