我的目标是:
computername中的用户类型为组合框
btn甚至启动一个新的backgroundworker线程将computername传递给DoWork方法
DoWork方法将预定义的目录和内容复制到输入的计算机名称上的预定义位置。
正在复制目录。我想在进度条中显示进度。我相信使用backgroundWorker1_ProgressChanged事件是你如何做到这一点。 (WorkReportsProgress属性设置为True)
在我的代码中,您可以看到我添加了一个方法来获取目录的大小。这可能,也可能不重要,但无论如何我都把它留在那里。如果与我的“目标”无关,请忽略。我也有一种轻微的感觉我正在复制数据的方式可能是问题,但我真的不知道。我还是新手。提前感谢您,我感谢您的帮助!
编辑我找到了这个惊人的例子here。这回答了我的大部分问题,但我仍然坚持让它在后台线程上正确运行。我应该使用backgroundworker来做这件事吗?
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;
}
答案 0 :(得分:1)
我相信你只需要添加类似
的内容int PercentageDone = 100* SizeOfFilesAlreadyCopied/TotalSizeOfAllFiles;
backgroundWorker1.ReportProgress(PercentageDone);
到你的foreach复制循环。您可以在ReportProgress方法中使用第二个参数来复制要显示的其他一些属性,但您需要使用一些简单的自定义容器类。
哦,请记住,您的backgroundWorker1_ProgressChanged
方法应该分配给后台工作人员
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
或只是从backgroundWorker
的属性菜单中选择它。
这里的简单例子
http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx