C# C“单词互操作-”;查找并替换“;查找单词但不替换它

C# C“单词互操作-”;查找并替换“;查找单词但不替换它,c#,replace,ms-word,find,interop,C#,Replace,Ms Word,Find,Interop,下面的代码能够找到我要查找的文本,但是当我去替换它时,文本没有被替换。我没有例外 var word = new Application(); File.Delete(@"Your new test document.docx"); File.Copy(@"Your test document.docx", @"Your new test document.docx"); var document = word.Documents.Open(@"Your new test document.doc

下面的代码能够找到我要查找的文本,但是当我去替换它时,文本没有被替换。我没有例外

var word = new Application();
File.Delete(@"Your new test document.docx");
File.Copy(@"Your test document.docx", @"Your new test document.docx");
var document = word.Documents.Open(@"Your new test document.docx");
document.Activate();

while (document.Content.Find.Execute(FindText: "([Tag"))
{
    var stringToReplace = document.Content.Text.Substring(document.Content.Text.IndexOf("([Tag"), document.Content.Text.IndexOf("])") + 2 - document.Content.Text.IndexOf("([Tag"));
    var replacement = stringToReplace.Replace("(", "").Replace(")", "");

    if (document.Content.Find.Execute(FindText: stringToReplace))
    {
        Console.WriteLine(stringToReplace);
        document.Content.Find.Execute(FindText: stringToReplace, ReplaceWith: replacement, Replace: WdReplace.wdReplaceOne);
    }
    else
        Console.WriteLine("Failed");
}

document.Close(true);
word.Quit();
Marshal.ReleaseComObject(document);
Marshal.ReleaseComObject(word);
Console.WriteLine("Done");
Console.ReadLine();
要测试代码,请执行以下操作:

  • 创建word文档
  • 将以下内容粘贴到其中:

    ([Tag LastName][Tag LastName])

    地址:2

    堆栈溢出

    拥有那辆rad车的教皇被命名为([Tag FirstName],[Tag LastName])

  • 在代码中保存和更新文件路径
  • 将此示例用于替换

    private void SearchReplace()
    {
        Word.Find findObject = Application.Selection.Find;
        findObject.ClearFormatting();
        findObject.Text = "find me";
        findObject.Replacement.ClearFormatting();
        findObject.Replacement.Text = "Found";
    
        object replaceAll = Word.WdReplace.wdReplaceAll;
        findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing,
            ref replaceAll, ref missing, ref missing, ref missing, ref missing);
    }
    

    您会注意到它声明了
    replaceAll=Word.WdReplace.wdReplaceAll
    ,然后将其传递到
    findObject.Execute
    ,而您传递的
    WdReplace.wdReplaceOne
    只会替换找到的第一个项。

    代码工作正常,我将表单字段和普通文本以及“查找和替换”混合在一起ms word提供的功能无法完全与此配合使用(同样,它能够找到它,但不能替换它)。

    目标是一次只替换一个,这样零件就可以了。我在另一个领域也有几乎相同(相同的替换代码,但不同的场景)的代码,这实际上是可行的。虽然我尝试了你发布的代码,但还是没有成功。