title: Why does this code write a "corrupt file" that Word cannot open (not even "Open and Repair")?
body: <p>I'm a newb, feel free talk down to me.
  Sorry to be so vague; the code executes and writes a corrupt file. I can't get into the corrupt file to observe any errors/anomolies.  The size does look like a sum of the files being merged.</p>
  
  <p>I've googled the snot outta this and can't find anything I can understand how to implement.</p>
  
  <p>The Word error on open is:
  The file cannot be open because there are problems with the contents</p>
  
  <p>and</p>
  
  <p>Word found unreadable content, do you want to continue?  </p>
  
  <p>When I click Yes I get the first error again &amp; then I'm out.</p>
  
  <p>THe documents have content controls with the same name, but I've modded this to only add 1 doc in an effort to see if dupe content types would be a problem; same corrupt file results.</p>
  
  <p>btw....my ultimate intent is to overwrite the "template" (...Aggregate Report.dotx) in place.  But I can't get a valid file saved ANYWHERE, so...... :-/</p>
  
  <pre><code>using System;   
  using System.IO;
  using System.ComponentModel;
  using System.Web;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;
  using Microsoft.SharePoint;
  using Microsoft.SharePoint.WebControls;
  using System.Linq;
  using DocumentFormat.OpenXml.Packaging;
  using DocumentFormat.OpenXml.Wordprocessing;
  using Word = DocumentFormat.OpenXml.Wordprocessing;
  
  
  namespace BobsDocMerger.VisualWebPart1
  {
  [ToolboxItemAttribute(false)]
  public class VisualWebPart1 : WebPart
  {
      // Visual Studio might automatically update this path when you change the Visual Web Part project item.
      private const string _ascxPath = @"~/_CONTROLTEMPLATES/BobsDocMerger/VisualWebPart1/VisualWebPart1UserControl.ascx";
  
      protected override void CreateChildControls()
      {
          System.Web.UI.Control control = this.Page.LoadControl(_ascxPath);
          Controls.Add(control);
          base.CreateChildControls();
          Button btnSubmit = new Button();
          btnSubmit.Text = "Assemble Documents";
          btnSubmit.Click += new EventHandler(btnSubmit_Click);
          Controls.Add(btnSubmit);
      }
  
      void btnSubmit_Click(object sender, EventArgs e)
      {
          SPFolder folder = SPContext.Current.ListItem.Folder;
          char[] splitter = { '/' };
          string[] folderName = folder.Name.Split(splitter);
          string filePrefix = @"Weekly/" + folderName[0] + "/" + folderName[0];
  
          SPFile template = folder.Files[filePrefix + " - Aggregate Report.dotx"];
          SPFile file;
          byte[] byteArray = template.OpenBinary();
  
          using (MemoryStream mem = new MemoryStream())
          {
              mem.Write(byteArray, 0, (int)byteArray.Length);
  
              using (WordprocessingDocument myDoc = WordprocessingDocument.Open(mem, true))
              {
                  MainDocumentPart mainPart = myDoc.MainDocumentPart;
                  //Loop thru content controls
                  foreach (Word.SdtElement sdt in mainPart.Document.Descendants&lt;Word.SdtElement&gt;().ToList())
                  {
                      Word.SdtAlias alias = sdt.Descendants&lt;Word.SdtAlias&gt;().FirstOrDefault();
                      if (alias != null)
                      {
                          //The 2 tags in the Report are AggregateHeader and AggregateBody
                          string sdtTitle = alias.Val.Value;
                          string sdtTag = sdt.GetFirstChild&lt;SdtProperties&gt;().GetFirstChild&lt;Tag&gt;().Val;
                          if (sdtTitle == "Merge")
                          {
                              for (int i = 0; i &lt; folder.Files.Count; i++)
                              {
                                  file = folder.Files[i];
                                  //Do all files that are NOT the Aggregate Report
                                  if (file.Name.IndexOf("Aggregate Report") == -1)
                                  {
                                      if (i == folder.Files.Count-1)
                                      {
                                          AddAltChunk(mainPart, sdt, file, true);
                                      }
                                      else
                                      {
                                          AddAltChunk(mainPart, sdt, file, false);
                                      }
                                  }
                              }
                          }
                      }
                  }
  
                  HttpResponse resp = HttpContext.Current.Response;
                  resp.ClearContent();
                  resp.ClearHeaders();
                  resp.AddHeader("Content-Disposition", "attachment; filename=Assembled Document.docx");
                  //resp.ContentEncoding = System.Text.Encoding.UTF8;
                  resp.ContentType = "application/msword";
                  resp.OutputStream.Write(mem.ToArray(), 0, (int)mem.Length);
                  resp.Flush();
                  resp.Close();
                  HttpContext.Current.ApplicationInstance.CompleteRequest();
              }
          }
      }
  
      protected int id = 1;
  
      void AddAltChunk(MainDocumentPart mainPart, Word.SdtElement sdt, SPFile filename,bool LastPass)
      {
          string altChunkId = "AltChunkId" + id;
          id++;
          byte[] byteArray = filename.OpenBinary();
  
          AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
          AlternativeFormatImportPartType.WordprocessingML, altChunkId);
  
          using (MemoryStream mem = new MemoryStream())
          {
              mem.Write(byteArray, 0, (int)byteArray.Length);
              mem.Seek(0, SeekOrigin.Begin);
              chunk.FeedData(mem);
          }
  
          Word.AltChunk altChunk = new Word.AltChunk();
          altChunk.Id = altChunkId;
          //Replace content control with altChunk information 
  
          DocumentFormat.OpenXml.OpenXmlElement parent = sdt.Parent;
          parent.InsertBefore(altChunk, sdt);
          if (LastPass) { sdt.Remove(); }
      }
  }
  }
  </code></pre>