title: C# return memory stream from OpenXML resulting to a corrupted word file
body: <p>I have a problem with a MemoryStream from OpenXML. I succeed with opening a Word file, changing it and downloading it through the HttpResponse if I do all the steps in a single method.</p>
  
  <p>But if I try to do it in two different classes (or methods) by returning the MemoryStream, I get a corrupted word file. I thought about a flushing or buffer problem but I don't find a solution.</p>
  
  <p>Here is the working code :</p>
  
  <pre><code>    public void FillTemplateOpenXmlWord(HttpResponse response)
      {
          string filePath = @"c:\template.docx";
          byte[] filebytes = File.ReadAllBytes(filePath);
  
          using (MemoryStream stream = new MemoryStream(filebytes))
          {
              using (WordprocessingDocument myDoc = WordprocessingDocument.Open(stream, true))
              {
                  // do some changes
                  ...
                  myDoc.MainDocumentPart.Document.Save();
              }
  
              string docx = "docx";
              response.Clear();
              response.ClearHeaders();
              response.ClearContent();
              response.AddHeader("content-disposition", "attachment; filename=\"" + docx + ".docx\"");
              response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
              response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
              stream.Position = 0;
              stream.CopyTo(response.OutputStream);
              response.End();
          }
      }
  </code></pre>
  
  <p>Here is the non-working code :</p>
  
  <pre><code>    public void OpenFile(HttpResponse response)
      {
          MemoryStream stream = this.FillTemplateOpenXmlWord();
  
          string docx = "docx";
          response.Clear();
          response.ClearHeaders();
          response.ClearContent();
          response.AddHeader("content-disposition", "attachment; filename=\"" + docx + ".docx\"");
          response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
          response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
          stream.Position = 0;
          stream.CopyTo(response.OutputStream);
          response.End();
      }
  
      public MemoryStream FillTemplateOpenXmlWord()
      {
          string filePath = @"c:\template.docx";
          byte[] filebytes = File.ReadAllBytes(filePath);
  
          using (MemoryStream stream = new MemoryStream(filebytes))
          {
              using (WordprocessingDocument myDoc = WordprocessingDocument.Open(stream, true))
              {
                  // do some changes
                  ...
                  myDoc.MainDocumentPart.Document.Save();
              }
  
              return stream;
          }
      }
  </code></pre>
  
  <p>Any idea ?</p>
  
  <p>thank you</p>