I've been porting an application from .net framework to .net 5. I'm trying to generate a word document by reading a template file, using Open-XML-PowerTools to replace some text, and saving the new version.
I can't get the "Save()" to do anything!
Here's some slightly simplified code which demonstrates the problem:
byte[] content = System.IO.File.ReadAllBytes("c:\\Temp\\myrequesttemplate.docx");
using (MemoryStream mstr = new MemoryStream())
{
mstr.Write(content, 0, content.Length);
using var docTest = WordprocessingDocument.Open(mstr, true);
{
docTest.ReplaceText("%NAME%", mrcrequest.RequesterName); // At this point, I can see by looking at the document.innerxml that the replacement has been successful.
docTest.MainDocumentPart.Document.Save();
}
using (FileStream fs = new FileStream("c:\\Temp\\TestWordDoc.docx", FileMode.CreateNew))
{
mstr.WriteTo(fs);
}
}
The file created is just a copy of the old file, without the replacement. I can see that the replacement succeeds using the debugger to look at the innerXML of the MainDocument. It just seems to not be writing back to the stream.
I've tried using .MainDocumentPart.PutXDocument();
instead of .Save()
- it makes no difference.
I'm using DocumentFormat.OpenXML version 2.12, System.IO.Packaging 5.0.0, and Open-XML-PowerTools 4.4.0
Any ideas anyone? It's driving me nuts!