2013-04-17 42 views
1

我正在研究一個程序,該程序會根據文件中的某些文本將文件分類到組中。大多數文件可能是.doc或.docx。在辦公室Word文檔中查找單詞

我的程序應該能夠將單詞列表與文件中的單詞進行比較。 我是C#的新手,我只學習編程,整個「讀取.doc文件」的事情都在我頭上,所以任何幫助都將不勝感激!

到目前爲止具有與辦公室做我的代碼的部分是:

CODE

if (Path.GetExtension(listBox1.SelectedItem.ToString()) == ".doc" || 
    Path.GetExtension(listBox1.SelectedItem.ToString()) == ".docx") 
{ 
    Microsoft.Office.Interop.Word.Document doc = 
     new Microsoft.Office.Interop.Word.Document(listBox1.SelectedItem.ToString()); 
    doc.Activate(); 
} 

編輯:

很抱歉,如果這個問題還不夠清楚。 我的問題是:

如何找到,如果文檔包含文本文件中包含的任何特定單詞。 我已閱讀了許多其他問題,答案和教程,它可能只是我,但我完全不明白。

+0

而問題是什麼? – Oscar

+0

難道你不能只通過普通的流媒體閱讀器閱讀文本,並通過尋找某些單詞的對象巡航? – Jonesopolis

+2

普通的streamreader不能理解word文件的文件格式,同樣的方式notepad.exe cant – Sayse

回答

0

你似乎是使用微軟的互操作類,所以你可以使用Outlook.Interop.Find

MSDN description and HOW TO

如果文檔中包含單詞的執行方法將返回true。

 StringBuilder sb = new StringBuilder(); 

     Word.Range rng = rodape.Range; 
     Word.Find find = rng.Find; 

     find.ClearFormatting(); 
     find.Replacement.ClearFormatting();//Only required if you will replace the text 
     if (find.Execute("textToBeFound", false)) 
     { 
      //The document contains the word 

     } 

另外一個例子,從微軟:

private void SelectionFind() { 

object findText = "find me"; 

Application.Selection.Find.ClearFormatting(); 

if (Application.Selection.Find.Execute(ref findText, 
    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, 
    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, 
    ref missing, ref missing)) 
{ 
    MessageBox.Show("Text found."); 
} 
else 
{ 
    MessageBox.Show("The text could not be located."); 
} } 

但是你有很多其他的方式來做到這一點..