2017-04-09 214 views
0

我有下面的代码将一些文件夹复制到不同的位置,如果用户有复选框选中该文件夹。背景工作进度条

我有一个backgroundworker和一个progresbar。我看到人们在这个网站,甚至在MSDN上给出了同样的例子与

for (int i = 0; i <= 100; i++) 
{ 
    // Report progress to 'UI' thread 
    backgroundWorker1.ReportProgress(i); 
    // Simulate long task 
    System.Threading.Thread.Sleep(100); 
} 

这是所有罚款和我得到它是如何工作的理念更新进度。但我想不出的是实现我的复选框,并复制文件夹,如果它被检查,然后更新进度栏取决于我有多少复选框。我将选中的方块计数并分配给prgbarmax。

这是我到目前为止有:

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) 
{   
    for (int i = 0; i < prgbarmax; i++) 
    { 
     int step = (i/prgbarmax) * 100; 
     if (test1) 
     { 
      //do the copy here 
      backgroundWorker1.ReportProgress(i);      
     } 

     if (tes2) 
     { 
      //do the copy here 
      backgroundWorker1.ReportProgress(i); 
     } 

     if (test3) 
     { 
      //do the copy here     
      backgroundWorker1.ReportProgress(i); 
     } 
     .... so on 
    } 
} 
+0

您使用的是WPF还是Windows Forms? – Transcendent

+0

您需要构建要复制的文件夹列表,并且在for循环的每次迭代中仅复制一个文件夹。你的代码的问题是你试图在一次迭代中复制所有的文件夹。 – kennyzx

+0

@kennyzx我对C#非常陌生,并且正在努力学习我的代码。你能给我一个代码示例吗? – Besiktas

回答

0

您需要构建要复制的文件夹列表,并在for循环的每个迭代只复制一个文件夹。你的代码的问题是你试图在一次迭代中复制所有的文件夹。

说明代码示例中的想法。

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) 
{ 
    //construct the list of folder to be copied 
    List<DirectoryInfo> listOfFolders = new List<DirectoryInfo>(); 
    if (test1) 
     listOfFolders.Add(folder1); 
    if (test2) 
     listOfFolders.Add(folder2); 
    if (test3) 
     listOfFolders.Add(folder3); 

    //begin to copy 
    for (int i = 0; i < listOfFolders.Count; i++) 
    { 
     listOfFolders[i].Copy(...); //copy only one folder in the list 
     int step = ((i + 1)/listOfFolders.Count) * 100; //calculate the progress 
     backgroundWorker1.ReportProgress(step); 
    } 
} 
+0

感谢您的代码。但是每个文件夹都被复制到不同的文件夹中。我如何比较名称并根据哪个文件夹进行复制? – Besiktas

+0

恩...但这与背景工作者的原始问题无关。为了确保每个问题/答案都有一个具体的背景,我建议你开始一个新的职位。 – kennyzx