3.代碼實現
1private void bwFileCopy_DoWork(object sender, DoWorkEventArgs e)
2 {
3 DirectoryInfo di = (DirectoryInfo)e.Argument;
4 int iCur = 1;
5 foreach (FileInfo fi in di.GetFiles())
6 {
7 //為證明ToolTrip對於跨線程的特殊性,在此處更新狀態欄的當前處理文件信息
8 //實際應用時最好放到ProgressChanged中,通過ReportProgress的參數UserState傳遞要處理的信息!
9 tsslInfo.Text = string.Format("當前正在拷貝文件:{0}", fi.Name);
10
11 fi.CopyTo(Path.Combine(targetDir,fi.Name),true);
12 bwFileCopy.ReportProgress(GetPercent(iCur, iFileCount),fi.Name);
13 iCur++;
14
15 }
16 e.Result = iCur;
17 }
18
19private void bwFileCopy_ProgressChanged(object sender, ProgressChangedEventArgs e)
20 {
21 //在此處更新狀態欄中的進度條
22 tssbProcess.Value = e.ProgressPercentage;
23
24 //在ListvIEw中添加拷貝信息
25 string FileName = e.UserState.ToString();
26 lvOutput.Items.Add(new ListVIEwItem(new string[] {System.DateTime.Now.ToLongTimeString (),FileName})).EnsureVisible();
27
28 }
29private void bwFileCopy_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
30 {
31 //清空源目錄和目標目錄
32 tbSource.Text = string.Empty;
33 tbTargetDir.Text = string.Empty;
34 //提示拷貝文件數量
35 MessageBox.Show(string.Format("此過程共拷貝了{0}個文件",e.Result));
36 }
37
4.運行結果