I'm trying to serve a word document (docx) from an asp.net page using the following code
protected void Page_Load(object sender, EventArgs e)
{
MemoryStream document = new MemoryStream();
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
SetMainDocumentContent(mainPart);
}
string fileName = "MsWordSample.docx";
Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.OutputStream.Write(document.ToArray(), 0, document.ToArray().Length);
}
public static void SetMainDocumentContent(MainDocumentPart part)
{
const string docXml =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
<w:body>
<w:p>
<w:r>
<w:t>Hello world!</w:t>
</w:r>
</w:p>
</w:body>
</w:document>";
using (Stream stream = part.GetStream())
{
byte[] buf = (new UTF8Encoding()).GetBytes(docXml);
stream.Write(buf, 0, buf.Length);
}
}
but I get the following message when trying to open the file: "the file {file name} cannot be opened because there are problems with the content"
I then get an option to recover the document which actually fixes the document.
Am I leaving something out?