我的目标是:
用户在组合框中输入计算机名
btn 甚至启动了一个新的后台工作线程,将计算机名传递给 DoWork 方法
DoWork 方法将预定义的目录和内容复制到输入的计算机名称上的预定义位置。
在复制目录时。我想在进度条中显示进度。我相信使用 backgroundWorker1_ProgressChanged 事件就是你这样做的方式。(WorkReportsProgress 属性设置为 True)
在我的代码中,您可以看到我添加了一个获取目录大小的方法。这可能重要,也可能不重要,但我还是把它留在了那里。如果与我的“目标”无关,请忽略。我也有一种轻微的感觉,我复制数据的方式可能是问题,但我真的不知道。我对这一切还是陌生的。提前感谢您,感谢您的帮助!
编辑我在这里找到了这个惊人的例子。这回答了我的大部分问题,但我仍然坚持让它在后台线程上正确运行。我应该使用后台工作人员来做到这一点吗?
private void button1_Click(object sender, EventArgs e)
{
//Start background worker thread. Passes computer name the user entered
backgroundWorker1.RunWorkerAsync(comboBox1.Text);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//Computer name user entered
string PCName = (string)e.Argument;
string DestinationPath = @"Remote PC C: Drive";
string SourcePath = @"Network share";
//Get File Size
DirectoryInfo dInfo = new DirectoryInfo(SourcePath);
long sizeOfDir = DirectorySize(dInfo, true);
//Use to output. File Size in MB
double size = sizeOfDir / (1024 * 1024);
//Creates Folder on remote PC
Directory.CreateDirectory(DestinationPath);
//Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
}
//Copy all the files
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done");
}
static long DirectorySize(DirectoryInfo dInfo, bool includeSubDir)
{
// Enumerate all the files
long totalSize = dInfo.EnumerateFiles()
.Sum(file => file.Length);
// If Subdirectories are to be included
if (includeSubDir)
{
// Enumerate all sub-directories
totalSize += dInfo.EnumerateDirectories()
.Sum(dir => DirectorySize(dir, true));
}
return totalSize;
}