天天看點

C#周遊檔案讀取Word内容以及使用BackgroundWorker對象打造平滑進度條

本文将給出一個執行個體用于介紹如何利用C#周遊目錄中的檔案并列印Word檔案中的内容,同時在界面上利用一個相對平滑的進度條來顯示檔案處理的情況。下面是程式運作時的截圖:

<a href="http://images.cnblogs.com/cnblogs_com/jaxu/201101/201101301415061462.png"></a>

  下面來看看程式的具體實作步驟。

  首先是讀取指定的目錄并周遊其中的檔案。這個功能很簡單,我們隻需要通過一個foreach循環周遊DirectoryInfo對象中的所有檔案即可。在本例中,我們定義了一個檔案夾選擇控件,當使用者點選Select按鈕時彈出對話框使用者指定程式要周遊的目錄,将目錄字元串存儲在文本框中。點選Go按鈕時開始周遊檔案夾中的所有檔案。程式将按行輸出目錄中Word檔案名,不包含擴充名。

<a></a>

1 using System; 

2 using System.Collections.Generic; 

3 using System.ComponentModel; 

4 using System.Data; 

5 using System.Drawing; 

6 using System.Linq; 

7 using System.Text; 

8 using System.Windows.Forms; 

9 using System.IO; 

10  

11 namespace ListFileName 

12 { 

13     public partial class ListFileName : Form 

14     { 

15         protected DirectoryInfo dirFolder = null; 

16  

17         public ListFileName() 

18         { 

19             InitializeComponent(); 

20         } 

21  

22         private void SelectPath() 

23         { 

24             if (folderBrowserDialog.ShowDialog() == DialogResult.OK) 

25             { 

26                 this.tbPath.Text = folderBrowserDialog.SelectedPath; 

27             } 

28         } 

29  

30         // Double click the path textbox to open the folder browser dialog. 

31         private void tbPath_DoubleClick(object sender, EventArgs e) 

32         { 

33             SelectPath(); 

34         } 

35  

36         // Open the folder browser dialog. 

37         private void btSelect_Click(object sender, EventArgs e) 

38         { 

39             SelectPath(); 

40         } 

41  

42         // Start to run. 

43         private void btGo_Click(object sender, EventArgs e) 

44         { 

45             this.btGo.Enabled = this.btSelect.Enabled = this.tbPath.Enabled = false; 

46             this.tbOutput.Text = ""; 

47             string folderPath = this.tbPath.Text.Trim(); 

48  

49             if (folderPath.Length == 0 || !Directory.Exists(folderPath)) 

50             { 

51                 MessageBox.Show("Please select a valid folder.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 

52                 return; 

53             } 

54             dirFolder = new DirectoryInfo(folderPath); 

55  

56             //Traversing file 

57             foreach (FileInfo file in dirFolder.GetFiles()) 

58             { 

59                 // if the file type is word and not the word temp file. 

60                 if (file.Extension.IndexOf("doc") &gt; 0 &amp;&amp; file.Name.IndexOf("~$") &lt; 0) 

61                 { 

62                     this.tbOutput.Text += file.Name.Substring(0, file.Name.LastIndexOf('.')).Trim() += "\r\n"; 

63                 } 

64             } 

65  

66             if (this.tbOutput.Text.Length &gt; 2) 

67             { 

68                 this.tbOutput.Text = this.tbOutput.Text.Substring(0, this.tbOutput.Text.Length - 2); 

69             } 

70  

71             this.btGo.Enabled = this.btSelect.Enabled = this.tbPath.Enabled = false; 

72         }         

73     } 

74 }

  然後是增加讀取Word檔案的功能。這個需要使用COM元件,在工程中添加對Word COM元件的引用。

 1 using Word = Microsoft.Office.Interop.Word;

 2 

 3 protected Word.Application app = null;

 4 protected Word.Document doc = null;

 5 

 6 private string ReadTextFromWord(object fileName)

 7 {

 8     string sRst = string.Empty;

 9     object isReadOnly = true;

10     object unknow = Type.Missing;

11     app.Visible = false;

12 

13     if (app != null)

14     {

15 

16         try

17         {

18             // Open a word document with read only mode.

19             doc = app.Documents.Open(ref fileName,

20                                      ref unknow, ref isReadOnly, ref unknow, ref unknow, ref unknow,

21                                      ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,

22                                      ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);

23 

24             // Read the second paragraph text - Production's Engligh name.

25             sRst = (doc.Paragraphs.Count &gt; 1 ? doc.Paragraphs[2].Range.Text.Trim() : "") + "\t";

26             // Read the third paragraph text - Production's Chinese name.

27             sRst += (doc.Paragraphs.Count &gt; 2 ? doc.Paragraphs[3].Range.Text.Trim() : "") + "\t";

28         }

29         catch (Exception)

30         {

31         }

32         finally

33         {

34             // Close opened word document.

35             app.ActiveDocument.Close(ref unknow, ref unknow, ref unknow);

36         }

37     }

38 

39     return sRst;

40 }

  注意打開Word文檔時可以以隻讀方式打開,這樣打開的速度會稍微快一點,并且關閉的時候不會出現是否儲存檔案的對話框。任何情況下隻要打開了Word文檔,一定記住使用完後要将其關閉,并且在退出程式時也要将Word程序一并關掉。

 1 // Kill the word process when closed main form.

 2 private void ListFileName_FormClosed(object sender, FormClosedEventArgs e)

 3 {

 4     if (app != null)

 5     {

 6         object unknow = Type.Missing;

 7         object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;

 8         app.Quit(ref saveChanges, ref unknow, ref unknow);

 9     }

10 }

  最後再來看看如何實作平滑進度條。這個需要使用到BackgroundWorker對象,該對象允許程式在多線程下執行,我們可以将界面UI和背景線程分開,這樣當程式在執行一個時間較長的任務時不會導緻主界面處于等待狀态,使用者仍然可以操作主界面上的元素,使程式看起來比較平滑。BackgroundWorker對象定義了一些屬性和委托用來處理多線程間的資訊同步,諸如背景線程在執行過程中如何通知主界面的線程更新進度條值等。

1 Application.EnableVisualStyles();

3 worker.WorkerReportsProgress = true;

5 worker.DoWork += new DoWorkEventHandler(worker_DoWork);

6 worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);

7 worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

  在work_DoWork中調用具體執行的方法,worker_ProgressChanged方法用來實時更新進度條值,worker_RunWorkerCompleted方法用來處理當背景線程執行完操作後要處理的事情,如更新界面UI,将進度條的目前值更改為100%等。可以看看下面完整的程式代碼:

ListFileName

<a href="http://files.cnblogs.com/jaxu/ListFileName.zip">完整代碼下載下傳</a>

本文轉自Jaxu部落格園部落格,原文連結:http://www.cnblogs.com/jaxu/archive/2011/01/30/1947826.html,如需轉載請自行聯系原作者