Advertisement
chmosama

How to Edit MS Word Text with C# Console Application

Nov 24th, 2014
590
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Runtime.InteropServices;
  2. using Microsoft.Office.Interop.Word;
  3.  
  4. namespace ConsoleApplication1
  5. {
  6.     class Program
  7.     {
  8.         static void Main()
  9.         {
  10.             const string documentLocation = @"C:\Users\chmosama\Desktop\Demo.docx"; //<-- File Location you want to edit
  11.             const string findText1 = "<firstname>"; //<-- The text you want to edit
  12.             const string replaceText1 = "Ch M"; //<-- The text you want to replace
  13.  
  14.             const string findText2 = "<lastname>"; //<-- The text you want to edit
  15.             const string replaceText2 = "Osama"; //<-- The text you want to replace
  16.  
  17.             FindReplace(documentLocation, findText1, replaceText1);
  18.             FindReplace(documentLocation, findText2, replaceText2);
  19.         }
  20.  
  21.         private static void FindReplace(string documentLocation, string findText, string replaceText)
  22.         {
  23.             var app = new Application();
  24.             var doc = app.Documents.Open(documentLocation);
  25.             var range = doc.Range();
  26.             range.Find.Execute(FindText: findText, Replace: WdReplace.wdReplaceAll, ReplaceWith: replaceText);
  27.             var shapes = doc.Shapes;
  28.             foreach (Shape shape in shapes)
  29.             {
  30.                 var initialText = shape.TextFrame.TextRange.Text;
  31.                 var resultingText = initialText.Replace(findText, replaceText);
  32.                 shape.TextFrame.TextRange.Text = resultingText;
  33.             }
  34.             doc.Save();
  35.             doc.Close();
  36.             Marshal.ReleaseComObject(app);
  37.         }
  38.     }
  39. }
Advertisement
RAW Paste Data Copied
Advertisement