title: Streaming In Memory Word Document using OpenXML SDK w/ASP.NET results in "corrupt" document
body: <p>I am unable to stream a word document that I create on the fly down to the browser. I am constantly getting a message from Microsoft Word that the document is corrupt. </p>
  
  <p>When I run the code via a Console Application and take ASP.NET out of the picture, the document is generated correctly with no problems. I believe everything centers around writing the file down.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>using (MemoryStream mem = new MemoryStream())
  {
      // Create Document
      using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
      {
          // Add a main document part. 
          MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
  
          new Document(new Body()).Save(mainPart);
  
          Body body = mainPart.Document.Body;
          body.Append(new Paragraph(new Run(new Text("Hello World!"))));
  
          mainPart.Document.Save();
          // Stream it down to the browser
  
          // THIS IS PROBABLY THE CRUX OF THE MATTER &lt;---
          Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
          Response.ContentType = "application/vnd.ms-word.document";
          mem.WriteTo(Response.OutputStream);
          Response.End();
      }
  }
  </code></pre>
  
  <p>I have <a href="https://stackoverflow.com/questions/9307993/asp-net-open-word-document">looked</a> at a lot of <a href="https://stackoverflow.com/questions/2477564/why-are-docx-files-being-corrupted-when-downloading-from-an-asp-net-page">links</a> – but nothing quite works. I lot of people use <code>MemoryStream.WriteTo</code> and some use <code>BinaryWrite</code> – at this point I'm not sure what the correct way is. Also I've tried the longer content type, i.e. <code>application/vnd.openxmlformats-officedocument.wordprocessingml.document</code> but no luck.</p>
  
  <p>Some screenshots – even if you try to recover you get the same "parts are missing or invalid"</p>
  
  <p><strong>Solution for those who stumble on this question:</strong></p>
  
  <p>Within the <code>using</code> directive of the <code>WordProcessingDocument</code>, you must call:</p>
  
  <pre><code>wordDocument.Save();
  </code></pre>
  
  <p>Also to correctly stream the <code>MemoryStream</code>, use this in the outer using block:</p>
  
  <pre><code>Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
  Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
  mem.Position = 0;
  mem.CopyTo(Response.OutputStream);
  Response.Flush();
  Response.End();
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/vTKxJ.png" alt="enter image description here">
  <img src="https://i.stack.imgur.com/h34kg.png" alt="enter image description here"></p>