如何使用 C# 替换 Microsoft WORD 中的双引号

How to replace double quotes in Microsoft WORD using C#

如果 WORD 文档中包含单词 Apple:

,则以下内容成功将 Apple 替换为 Mango
myDocRange.Find.Execute(FindText: "Apple", Format: false, ReplaceWith: "Mango", MatchWildcards: true, Replace: Word.WdReplace.wdReplaceAll);

但是如果文档有双引号 " 并且您想将其替换为 TEST,则以下内容不执行任何操作:

myDocRange.Find.Execute(FindText: "\"", Format: false, ReplaceWith: "TEST", MatchWildcards: true, Replace: Word.WdReplace.wdReplaceAll);

备注:如果我不使用"\"",如果我使用""""@""",我会得到一个语法错误。

但是,以下在 VBA 中有效。但我需要它在 C#:

中工作
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = """"
    .Replacement.Text = "TEST"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

使用字符代码查找特殊字符,根据MSDN:

查找文本:

You can search for special characters by specifying appropriate character codes. For example, "^p" corresponds to a paragraph mark and "^t" corresponds to a tab character.

所以你需要使用 ^34 作为 ":

myDocRange.Find.Execute(FindText: "^34", Format: false, ReplaceWith: "TEST", MatchWildcards: true, Replace: Word.WdReplace.wdReplaceAll);