I have a requirement to read an existing MS Word 2007 file (.docx), replace string1 with string2 and then attached the "newly editted" file as an attachment on an email "on the fly".
We are using v2.0 of Microsoft DocumentFormat.OpenXml SDK and .NET 4.5 (C#)
This has stumped me because:
- I am trying to do it without editting the original file; or
- Copying the original file and then editting it; or
- Saving a new file to disk (and then deleting it); or
- Changing the file format e.g. to .XML
The following code is taken from another stackoverflow question but works with editing the orignal file on disk.
I'm stuck how to pass the documentText to the attachment constructor as a MemoryStream. The email that is generated is corrupted and is way bigger than the orignal file size. I have tried GzipStream and no joy :-(
string sourceFilePath = @"C:\Template.docx";
string documentText;
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(sourceFilePath, true))
{
using (StreamReader reader = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
documentText = reader.ReadToEnd();
}
documentText = documentText.Replace("searchstring", "replacementstring");
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(documentText);
}
MailMessage email = new MailMessage();
email.Attachments.Add(new Attachment(sourceFilePath));
// Send email etc
}
Cheers
kyle