'find and replace text in the entire document including headers

Document example (Opens correctly in MS Office)

I have a Word document 1 where I need to replace all tags <> in the text with my values. Using the interop, I got access to the main text and the text of the Headers for seaching matches by Regex class,

    static string GetContent(Word.Document document)
    {
        return document.Content.Text;
    }

    static string GetHeaderFooterText(Word.Document document)
    {
        StringBuilder sb = new StringBuilder();
        foreach (Word.Section section in document.Sections)
        {
            foreach (Word.HeaderFooter hf in section.Headers)
            {
                if (!hf.Exists)
                    continue;
                Word.Range range = hf.Range;
                sb.AppendLine(range.Text);
                foreach (Word.Shape shape in hf.Shapes)
                {
                    sb.AppendLine(shape.TextFrame.TextRange.Text);
                }
            }

        }
        return sb.ToString();
    }

    public string[] GetMatches(string pattern, string text)
    {
        WordReader reader = new WordReader(Word);

        Regex regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);

        HashSet<string> matches = new HashSet<string>();

        foreach(Match match in regex.Matches(text))
            matches.Add(match.Value);

        return matches.ToArray();
    }

but I can’t get the text from the tables located in the Headers. The value of the number of tables property of the HeaderFooter class is 0. Replacing text with the Find class also does not replace tags in these tables.

private void ReplaceWords(Word.Application app, Dictionary<string, string> keyValuePairs)
    {
        foreach (var pair in keyValuePairs)
        {
            Word.Find find = app.Selection.Find;

            find.ClearFormatting();
            find.Replacement.ClearFormatting();

            find.Text = pair.Key;
            find.Replacement.Text = pair.Value;
            find.MatchAllWordForms = false;
            find.Forward = true;
            find.Wrap = Word.WdFindWrap.wdFindContinue;
            find.Forward = false;
            find.MatchCase = false;
            find.MatchWholeWord = false;
            find.MatchWildcards = false;
            find.MatchSoundsLike = false;

            find.Execute(Replace: Word.WdReplace.wdReplaceAll);
        }
    }

Is there a way to access these tables and how to replace text in the document globally at all levels?



Solution 1:[1]

I found a working way to access all document content:

foreach (Word.Range range in wordApp.ActiveDocument.StoryRanges)
{
    //Get string range.Text or use range.Find to find and replace text in document
}  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Badunsutra