2013-11-25 90 views
3

我有一個應用程序,我正在寫複製文件。我有文件複製沒有任何問題,但由於某種原因,進度欄不更新。我正在使用後臺工作人員。這裏是代碼:文件複製進度欄不更新。文件複製工作正常

private void bgWorker_DoWork(object sender, DoWorkEventArgs e) 
     { 
      // Gets the size of the file in bytes. 
      Int64 iSize = strInputFile.Length; 

      // Keeps track of the total bytes downloaded so we can update the progress bar. 
      Int64 iRunningByteTotal = 0; 
       // Open the input file for reading. 
      using (FileStream InputFile = new FileStream(strInputFile, FileMode.Open, FileAccess.Read, FileShare.None)) 
      { 
       // Using the FileStream object, we can write the output file. 
       using (FileStream OutputFile = new FileStream(strOutputFile, FileMode.Create, FileAccess.Write, FileShare.None)) 
       { 
        // Loop the stream and get the file into the byte buffer. 
        int iByteSize = 0; 
        byte[] byteBuffer = new byte[iSize]; 
        while ((iByteSize = InputFile.Read(byteBuffer, 0, byteBuffer.Length)) > 0) 
        { 
         // Write the bytes to the file system at the file path specified. 
         OutputFile.Write(byteBuffer, 0, iByteSize); 
         iRunningByteTotal += iByteSize; 

         // Calculate the progress out of a base "100." 
         double dIndex = (double)(iRunningByteTotal); 
         double dTotal = (double)byteBuffer.Length; 
         double dProgressPercentage = (dIndex/dTotal); 
         int iProgressPercentage = (int)(dProgressPercentage * 100); 
         // Update the progress bar. 
         bgWorker.WorkerReportsProgress = true; 
         bgWorker.ReportProgress(iProgressPercentage); 
        } 
        // Close the output file. 
        OutputFile.Close(); 
       } 
       // Close the input file. 
       InputFile.Close(); 
      } 
     } 

     private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) 
     { 
      // We will increase the progress bar when work progress is reported. 
      pbCopyProgress.Value = e.ProgressPercentage; 
      pbCopyProgress.Text = (e.ProgressPercentage.ToString() + " %"); 
     } 

     private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
     { 
      // Disable the Copy button once the file has been copied. 
      MessageBox.Show("The file: "+strOutputFile+" has been copied"); 
      btnCopy.Enabled = false; 
     } 
+0

此行'bgWorker.WorkerReportsProgress = TRUE;'應該是你的'bgWorker_DoWork'方法之外,也許在你的窗體構造函數(你通常做「視覺上」,而不是編程)。 – Jigsore

+0

嘗試在您的窗體構造函數中替換您的'bgWorker.WorkerReportsProgress = true;' – Rohit

+0

我已經修復了bgWorker.WorkerReportsProgress = true; – Tornado726

回答

0

我發現我需要初始化我的後臺工作人員事件處理程序,以解決我遇到的問題。我只是需要以下三行添加在窗體加載事件:

bgWorker.DoWork += bgWorker_DoWork; 
bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted; 
bgWorker.ProgressChanged += bgWorker_ProgressChanged; 
+0

爲了將來的參考,您可以使用Visual Studio窗體編輯器自動創建Backgroundworker對象並自動連接所有事件處理程序 - BackgroundWorker位於Forms工具箱中,並且可以像任何其他窗體控件一樣工作按鈕,文本框等),除了它在運行時在窗體上不可見。 –