C# Perform a Find/Replace in a word document


I have to find/replace text from a word document. It works fine for plain text spread through the document, however when the text is in a textbox, the standard find/replace approach doesn't reach it.

Here is the code for the find/replace that only works with plain text (not in word textbox objects):

 private void FindAndReplace(Word.Application WordApp,
                                    object findText,
                                    object replaceWithText)
            object matchCase = false;
            object matchWholeWord = false;
            object matchWildCards = false;
            object matchSoundsLike = false;
            object nmatchAllWordForms = false;
            object forward = true;
            object format = false;
            object matchKashida = false;
            object matchDiacritics = false;
            object matchAlefHamza = false;
            object matchControl = false;
            object read_only = false;
            object visible = true;
            object replace = 2;
            object wrap = 1;

            WordApp.Selection.Find.Execute(ref findText,
                ref matchCase, ref matchWholeWord,
                ref matchWildCards, ref matchSoundsLike,
                ref nmatchAllWordForms, ref forward,
                ref wrap, ref format, ref replaceWithText,
                ref replace, ref matchKashida,
                ref matchDiacritics, ref matchAlefHamza,
                ref matchControl);
Who is Participating?
Meir RivkinConnect With a Mentor Full stack Software EngineerCommented:
here's your solution:

u need to get the textbox object, then use "text" property to read the text in the textbox control.
koldstarAuthor Commented:

 But InlineShapes contains no objects?
koldstarAuthor Commented:

it just skips the for loop. If I run the Count method it also returns 0.

After some testing I think that the textboxes might be inside an image object. So I guess I have to loop through them first? But how do I do that.
Right now I'm working on another solution where I save the documents as XML first and then do a REGEX "seach and replace". It Seeems to work fine, but It would be nice to know how to do the other way around.

OrcbighterConnect With a Mentor Commented:
The trouble with Word is that it is a multi-layered container. Text sits at a higher layer than objects like TextBoxes.
Another example is captions for graphics: The caption and the graphic sit at different layers within the document, which is why they can become separated if the picture is anchored and you add text, or move the picture.
A text search and replace solution would have to be quote complex to ensure you were accessing text at whatever layer it appeared at.
I think your XML solution, which you say works, is a good solution.

koldstarAuthor Commented:
Found another solution
All Courses

From novice to tech pro — start learning today.