I am looking for alternate ways to search through the word document for certain text and then replace it with another text. My current works using the Find and Replace method however I was wondering if there are other ways to do this.
One method I tried was to go through paragraph by paragraph and search that for the text, swap it out, then paste that into a new word document and save it. However this made things a lot more complicated when it came to images, textbooks, tables etc. Also the formatting did not get preserved so that was another issue.
My current code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
namespace Test
{
static class Program
{
static void Main()
{
//Create a new microsoft word file
Microsoft.Office.Interop.Word.Application fileOpen = new Microsoft.Office.Interop.Word.Application();
//Open a already existing word file into the new document created
Microsoft.Office.Interop.Word.Document document = fileOpen.Documents.Open(@"C:\Users\dpatel\Desktop\Test1.docx", ReadOnly: false);
//Make the file visible
fileOpen.Visible = true;
document.Activate();
//The FindAndReplace takes the text to find under any formatting and replaces it with the
//new text with the same exact formmating (e.g red bold text will be replaced with red bold text)
FindAndReplace(fileOpen, "useless", "very useful");
//Save the editted file in a specified location
//Can use SaveAs instead of SaveAs2 and just give it a name to have it saved by default
//to the documents folder
document.SaveAs2(@"C:\Users\dpatel\Desktop\NewFile1");
//Close the file out
fileOpen.Quit();
}
//Method to find and replace the text in the word document. Replaces all instances of it
static void FindAndReplace(Microsoft.Office.Interop.Word.Application fileOpen, object findText, object replaceWithText)
{
object matchCase = false;
object matchWholeWord = true;
object matchWildCards = false;
object matchSoundsLike = false;
object matchAllWordForms = 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;
//execute find and replace
fileOpen.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
}
}
}
Turns out there is no alternative to finding and replacing text. The only way is to scan a document, extract text, then if it matches, to issue a replacement. Which is essentially the same as "find and replace". There are variations to the method however like choosing to search through textboxes only, tables only etc.