gpt4 book ai didi

c# - 在c#中搜索word文档

转载 作者:行者123 更新时间:2023-12-04 16:49:40 24 4
gpt4 key购买 nike

我正在制作一个搜索模块(C# 中的 windows 窗体)。它适用于 .txt 文件但我也需要在Word文档中搜索这个词。我尝试使用 Microsoft.Office.Interop.Word;代码如下

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document docOpen = app.Documents.Open(flname);
StreamReader srObj = new StreamReader(flname);
string read = srObj.ReadToEnd();
if (read.Contains(txtWordInput.Text)) // searching for the input word in the file
{
count1++;
lbSearchList.Visible = true;
lbSearchList.Items.Add(flname);
}
srObj.Close();
app.Documents.Close();

但它在运行时给出了一个错误,即 doc 文件已经打开,因此即使文档未打开也无法访问。

然后我尝试简单地使用流阅读器,它工作并确实读取了文件,但读取的数据是一些随机符号,而不是实际写入的内容。由于这个 if (read.Contains(txtWordInput.Text)) 语句无法搜索单词。

请帮我写出如何在word文档中成功搜索单词的代码。

最佳答案

使用该代码,看起来错误是正确的。您尝试打开文档两次。首先使用“app.Documents.Open(flname)”行,然后再次创建具有相同文件名的 StreamReader 对象。另外,word 文档不是文本文件,而是实际上包含其他文件的 zip 文件。因此,如果您只是尝试使用 StreamReader 将文件作为文本读取,您将得到准确的结果……一堆符号。

使用此方法可以简单地读取文本并在 Word 文件中搜索特定字符串。还要确保使用正确的语句。

using Word = Microsoft.Office.Interop.Word;

public static Boolean CheckWordDocumentForString(String documentLocation, String stringToSearchFor, Boolean caseSensitive = true)
{
// Create an application object if the passed in object is null
Word.Application winword = new Word.Application();

// Use the application object to open our word document in ReadOnly mode
Word.Document wordDoc = winword.Documents.Open(documentLocation, ReadOnly: true);

// Search for our string in the document
Boolean result;
if (caseSensitive)
result = wordDoc.Content.Text.IndexOf(stringToSearchFor) >= 0;
else
result = wordDoc.Content.Text.IndexOf(stringToSearchFor, StringComparison.CurrentCultureIgnoreCase) >= 0;

// Close the document and the application since we're done searching
wordDoc.Close();
winword.Quit();

return result;
}

然后要使用该方法,只需像调用任何其他静态方法一样调用它。

MyClass.CheckWordDocumentForString(@"C:\Users\CoolDude\Documents\MyWordDoc.docx", "memory", false);

使用你的代码会更像这样:

if (MyClass.CheckWordDocumentForString(flname, txtWordInput.Text, false))
{
// Do something if it is found
}
else
{
// Do something if it is not found
}

关于c# - 在c#中搜索word文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24691347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com