...
Code Block |
---|
string SearchPattern = "[Ww]ord[Ww]riter"; string replaceWith = "SoftArtisans"; string docPath = @"..\..\WordTemplateFiles\SearchReplace.doc"; /// <summary> /// Searches a document for a Regular Expression search term /// and replaces all instances of that term with a new string. /// The revised document is then saved. /// </summary> public void SearchDocument() { /* Open the document you wish to search */ WordApplication WordApplication wordApp = new WordApplication(); Document doc = wordApp.Open(docPath); /* Execute the replacement by specifying the search term * as a Regular Expression string, and the replacement string. * SearchAndReplace will return the number of replacements made. */ int numReplacements = doc.SearchAndReplace(SearchPattern, replaceWith); /* If no occurrences of the search pattern were found in the doc, display * a message and return. */ if(numReplacements == 0) { Console.WriteLine("Note: No occurrences of \"{0}\" were found in the document. " + "Please try another search pattern.", SearchPattern); return; } /* Prepend a message to the beginning of the document noting * how many replacements were made. */ string text = String.Format("Replaced {0} instances of \"{1}\" with \"{2}\"", numReplacements, SearchPattern, replaceWith); /* Create a new paragraph and insert the note */ Paragraph pg = doc.InsertParagraphBefore(null); pg.InsertTextAfter(text, false); /* Save the edited document */ wordApp.Save(doc, @"..\..\WordOutputFiles\Replaced_out.doc"); } } |
...