Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Runtime.InteropServices;
- using Microsoft.Office.Interop.Word;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main()
- {
- const string documentLocation = @"C:\Users\chmosama\Desktop\Demo.docx"; //<-- File Location you want to edit
- const string findText1 = "<firstname>"; //<-- The text you want to edit
- const string replaceText1 = "Ch M"; //<-- The text you want to replace
- const string findText2 = "<lastname>"; //<-- The text you want to edit
- const string replaceText2 = "Osama"; //<-- The text you want to replace
- FindReplace(documentLocation, findText1, replaceText1);
- FindReplace(documentLocation, findText2, replaceText2);
- }
- private static void FindReplace(string documentLocation, string findText, string replaceText)
- {
- var app = new Application();
- var doc = app.Documents.Open(documentLocation);
- var range = doc.Range();
- range.Find.Execute(FindText: findText, Replace: WdReplace.wdReplaceAll, ReplaceWith: replaceText);
- var shapes = doc.Shapes;
- foreach (Shape shape in shapes)
- {
- var initialText = shape.TextFrame.TextRange.Text;
- var resultingText = initialText.Replace(findText, replaceText);
- shape.TextFrame.TextRange.Text = resultingText;
- }
- doc.Save();
- doc.Close();
- Marshal.ReleaseComObject(app);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement