简体   繁体   English

在文件传输过程中使用backgroundworker更新进度栏

[英]Update Progress bar using backgroundworker during file transfer

My goal here is: 我的目标是:

  • User types in computername into combobox 用户在组合框中输入计算机名

  • btn even starts a new backgroundworker thread passing the computername to the DoWork method btn甚至启动一个新的backgroundworker线程,将计算机名传递给DoWork方法

  • DoWork method copies a predefined directory and contents to a predefined location on the computer name that was entered. DoWork方法将预定义的目录和内容复制到输入的计算机名称上的预定义位置。

  • While the directory is being copied. 复制目录时。 I would like to display the progress in a progress bar. 我想在进度栏中显示进度。 I believe using the backgroundWorker1_ProgressChanged event is how you do this. 我相信使用backgroundWorker1_ProgressChanged事件是您执行此操作的方式。 (WorkReportsProgress propery is set to True) (WorkReportsProgress属性设置为True)

In my code, you can see i added a method to get the size of the directory. 在我的代码中,您可以看到我添加了一种获取目录大小的方法。 This may, or may not be important but i left it in there anyways. 这可能重要,也可能不重要,但是我还是把它留在了那里。 Please ignore if irrelevant to my 'goal'. 如果与我的“目标”无关,请忽略。 I also have a slight feeling the way I'm going about copying the data might be the issue but i really have no idea. 我也有一点感觉,我打算复制数据的方式可能是问题,但我真的不知道。 I'm still new to all this. 我还是所有这一切的新手。 Thank you in advance and i appreciate any assistance! 在此先感谢您,感谢您的协助!

EDIT I found this amazing example here . 编辑我在这里找到了这个惊人的例子。 This answers most of my question but I'm still stuck on getting this to correctly run on a background thread. 这回答了我的大部分问题,但是我仍然坚持让它在后台线程上正确运行。 Should i be using backgroundworker to do this? 我应该使用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;
}   

I believe you only need to add something like 我相信你只需要添加类似

int PercentageDone = 100* SizeOfFilesAlreadyCopied/TotalSizeOfAllFiles;

backgroundWorker1.ReportProgress(PercentageDone);

to your foreach copying loop. 到您的foreach复制循环。 You could use a second argument in ReportProgress method to copy some other attributes to display, though you'd need to use some simple custom container class. 您可以在ReportProgress方法中使用第二个参数来复制其他一些要显示的属性,尽管您需要使用一些简单的自定义容器类。 Oh and remember, that your backgroundWorker1_ProgressChanged method should be assigned to the backgroundworker itself 哦,请记住,应该将backgroundWorker1_ProgressChanged方法分配给backgroundworker本身。

backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);

or just by selecting it from backgroundWorker 's properties menu. 或者只是从backgroundWorker的属性菜单中选择它。

Simple examples here 这里的简单例子

http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM