c# Office Interop 在循环遍历大型文档中的每个单词时变慢

c# Office Interop Slow When Looping through each word in a large document

我有以下代码段,它循环遍历 Word 文档中的每个单词,找到加粗的行(句子)并将它们存储在列表中,MasterSentences

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
Document doc = new Document();
object path = fileDialog.FileName;
object missing = Type.Missing;

doc = word.Documents.Open(ref path, 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, ref missing);
string sentence = "";
foreach (Range rng in doc.StoryRanges)
{
    foreach (Range rngWord in rng.Words)
    {
        if ((rngWord.Text.Contains("\n") || rngWord.Text.Contains("\r")) && sentence != "")
        {
            MasterSentences.Add(sentence);
            sentence = "";
        }
        else if (rngWord.Bold != 0 && rngWord.Text != " " && rngWord.Text != "\t")
        {
            sentence += rngWord.Text;
        }
    }
}

问题是,对于包含 23,742 个单词的 Word 文档,这大约需要 3-4 分钟才能完成。

有什么办法可以提高速度吗?有没有更有效的方法来完成这个?

感谢大家的所有反馈。似乎使用 Range.Find.Execute 是正确的方法。这是我更新的大部分工作代码。现在只需要大约 20 秒,非常完美。

Range rngFindBold = doc.Range();
rngFindBold.Find.Font.Bold = 1;
while (rngFindBold.Find.Execute(Format: true))
{
    if (!string.IsNullOrWhiteSpace(rngFindBold.Text))
    {
        MasterSentences.Add(rngFindBold.Text);
    }
}