2011-12-10 49 views
0

我有點問題。我試圖製作一個表格,用狀態欄複製從A點到B點的東西。現在複製工作正常,但狀態欄只是沒有做任何事情.. 任何人有任何線索?複製進度條不起作用

public partial class Form4A : Form 
{ 
    public Form4A() 
    { 
     InitializeComponent(); 
     OtherSettings(); 
     BackgroundWorker.RunWorkerAsync(); // Starts wow copying 
    } 

    private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) 
    { 
     string SourcePath = RegistryRead.ReadOriginalPath(); 
     string DestinationPath = RegistryRead.ReadNewPath(); 

     if (!Directory.Exists(SourcePath)) 
     { 
      for (int i = 1; i <= 100; i++) 
      { 
       //Now 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)); 


       BackgroundWorker.ReportProgress(i); 
      } 
     } 
    } 
    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     // Change the value of the ProgressBar to the BackgroundWorker progress. 
     progressBar1.Value = e.ProgressPercentage; 
     // Set the text. 
     this.Text = e.ProgressPercentage.ToString(); 
    } 

} 
+0

確定的目標路徑已不存在,你調用這個函數之前?此外,它看起來像你沒有正確呈現進度更新,而是你複製100次所有文件。 –

+0

它應該'如果(Directory.Exists(SourcePath))'沒有「!」。 –

回答

1

你說:if (!Directory.Exists(DestinationPath))。這意味着如果存在目標路徑,則循環將永遠不會執行。確保在測試代碼之前刪除DestinationPath!

編輯:

if (Directory.Exists(SourcePath)) { 
    //Now Create all of the directories 
    string[] allDirectories = Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories); 
    string[] allFiles = Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories); 
    int numberOfItems = allDirectories.Length + allFiles.Length; 
    int progress = 0; 

    foreach (string dirPath in allDirectories) { 
     Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath)); 
     progress++; 
     BackgroundWorker.ReportProgress(100 * progress/numberOfItems); 
    } 

    //Copy all the files 
    foreach (string newPath in allFiles) { 
     File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath)); 
     progress++; 
     BackgroundWorker.ReportProgress(100 * progress/numberOfItems); 
    } 
} 
+0

tss,謝謝你指出,它應該是源路徑...事情是我剛剛從互聯網上得到這段代碼,因爲我不知道它是如何工作的 – user1071461

+0

所以你只是複製代碼,沒有實際分配ProgressChanged事件?在設計器中選擇BGW,單擊屬性窗口中的閃電圖標,然後雙擊ProgressChanged。 –

+0

並且還檢查是否也分配了DoWork事件處理程序。 –