Replace words on MS Word using C#

Hi,

Recently I was instructed to create an application that will be able to replace an array of words and replace them with an array of corresponding words on an MS Word document. With this I’ve searched the following:

Prerequisites

  1. Visual Stduio
  2. Install the nuget package DocX
  3. Administrative access on the context the application is running

Code

Dictionary<string, string> lReplacements = new Dictionary<string, string>();
string newFullPath = @”c:\sample.docx”;

using (DocX document = DocX.Load(newFullPath))
{

//for loop is better than foreach
foreach (var item in lReplacements)
{

document.ReplaceText(item.Key, item.Value);

}
document.Save();

}

Hope it helped you as it helped me with this simple snippet.

God Bless!
Thanks,
Thomie

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.