How to replace string on MS Word using XML SDK 2.0

using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);

using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
{
MainDocumentPart docPart = doc.MainDocumentPart;

foreach (HeaderPart header in docPart.HeaderParts)
{
string headerText = null;
using (StreamReader sr = new StreamReader(header.GetStream()))
{
headerText = sr.ReadToEnd();
}

if (headerText.Contains(oldString))
{
Regex regexText = new Regex(oldString);
headerText = regexText.Replace(headerText, newString);

using (StreamWriter sw = new StreamWriter(header.GetStream(FileMode.Create)))
{
sw.Write(headerText);
}
header.Header.Save();

isUpdate = true;

}
}

}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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