Hi!
I need to do a simple search and replace of a string in a word document. I thought it would be pretty easy, but it's not (at least for me)
Check out this code (It takes a stream, opens the different part of the doc, searches for the string, and then it replaces it).
Problem is that only whats inside the MainDocumentPart and the FooterPart is saved. The HeaderPart is not saved. Strange...
public static void ProcessDocument(Dictionary<string, string> properties, Stream fs)
{
using (WordprocessingDocument doc = WordprocessingDocument.Open(fs, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(doc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
docText = DoTheReplace(properties, docText);
using (StreamWriter sw = new StreamWriter(doc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
foreach (FooterPart footer in doc.MainDocumentPart.FooterParts)
{
string footerText = null;
using (StreamReader sr = new StreamReader(footer.GetStream()))
{
footerText = sr.ReadToEnd();
}
footerText = DoTheReplace(properties, footerText);
using (StreamWriter sw = new StreamWriter(footer.GetStream(FileMode.Create)))
{
sw.Write(footerText);
}
}
foreach (HeaderPart header in doc.MainDocumentPart.HeaderParts)
{
string headerText = null;
using (StreamReader sr = new StreamReader(header.GetStream()))
{
headerText = sr.ReadToEnd();
}
headerText = DoTheReplace(properties, headerText);
using (StreamWriter sw = new StreamWriter(header.GetStream(FileMode.Create)))
{
sw.Write(headerText);
}
}
}
}
And yes if there are simpler ways of replacing a string in a word doc, please let me know.
Thanks for any help
Larsi