2011-12-11 46 views
3

我試圖把我的文件複製表單上的進度,得到它的工作,但進度欄更新的基礎上的文件數量。問題是有很多小文件,還有一些非常大的文件需要複製。使用字節複製文件+進度條

所以我想知道如果不是使用文件編號,而是有辦法檢查正在寫入的字節數。 任何建議,非常感謝。下面是代碼我現在有:

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

     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); 
      } 
     } 

    } 

    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     // Change the value of the ProgressBar to the BackgroundWorker progress. 
     progressBar1.Value = e.ProgressPercentage; 
    } 

在此先感謝

回答

1

如果你想這個做自己,你可以

  1. 迭代計算的總規模中的所有文件被複制。
  2. 調用CopyFileEx進行復制。這使用回調機制來報告進度,並且回調包括爲當前文件複製的字節數。
  3. 記錄總共複製了多少個字節,並使用它來報告總體進度。

很可能是一個.net管理的等效於CopyFileEx。

但是,我建議您致電SHFileOperation,讓系統爲您做好工作。當你發現這項任務非常難以做好。作爲使用shell執行工作的額外好處,您將獲得標準系統對話框。

0

您需要實現自己的文件複製代碼,並從那裏報告進展情況。

編輯: 如果你不希望這些文件複製自己,你可以開始另一後臺工作,將檢查文件的複製進度(獲得當前拷貝文件的屬性,並檢查其長度) 。如果您沒有遇到共享問題,它會爲您提供更新進度欄所需的信息。

+0

用戶做已經,但它是被證明麻煩的細節。 –

+0

我可能會在這裏失明。它在哪裏說呢? – zmbq

+0

用戶已經完成了您所描述的內容,但遇到了細節問題。對於不同大小的文件,進度條不會以統一的速率移動。因此需要在進度計算中考慮文件大小。 –