title: how can I put a content in a mergefield in docx
body: <p>I'm developing a web application with asp.net and I have a file called Template.docx that works like a template to generate other reports. Inside this Template.docx I have some MergeFields (Title, CustomerName, Content, Footer, etc) to replace for some dynamic content in C#. </p>
  
  <p>I would like to know, how can I put a content in a mergefield in docx ?</p>
  
  <p>I don't know if MergeFields is the right way to do this or if there is another way. If you can suggest me, I appreciate!</p>
  
  <p>PS: I have openxml referenced in my web application.</p>
  
  <p>Edits:</p>
  
  <pre><code>private MemoryStream LoadFileIntoStream(string fileName)
  {
      MemoryStream memoryStream = new MemoryStream();
      using (FileStream fileStream = File.OpenRead(fileName))
      {
          memoryStream.SetLength(fileStream.Length);
          fileStream.Read(memoryStream.GetBuffer(), 0, (int) fileStream.Length);
  
          memoryStream.Flush();
          fileStream.Close();
      }
      return memoryStream;
  }
  
  public MemoryStream GenerateWord()
  {
      string templateDoc = "C:\\temp\\template.docx"; 
      string reportFileName = "C:\\temp\\result.docx";
  
      var reportStream = LoadFileIntoStream(templateDoc);
  
      // Copy a new file name from template file
      //File.Copy(templateDoc, reportFileName, true);
  
      // Open the new Package
      Package pkg = Package.Open(reportStream, FileMode.Open, FileAccess.ReadWrite);
  
      // Specify the URI of the part to be read
      Uri uri = new Uri("/word/document.xml", UriKind.Relative);
      PackagePart part = pkg.GetPart(uri);
  
      XmlDocument xmlMainXMLDoc = new XmlDocument();
      xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read));
  
      // replace some keys inside xml (it will come from database, it's just a test)
      xmlMainXMLDoc.InnerXml = xmlMainXMLDoc.InnerXml.Replace("field_customer", "My Customer Name");
      xmlMainXMLDoc.InnerXml = xmlMainXMLDoc.InnerXml.Replace("field_title", "Report of Documents");
      xmlMainXMLDoc.InnerXml = xmlMainXMLDoc.InnerXml.Replace("field_content", "Content of Document");
  
      // Open the stream to write document
      StreamWriter partWrt = new StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write));
      //doc.Save(partWrt);
      xmlMainXMLDoc.Save(partWrt);
  
      partWrt.Flush();
      partWrt.Close();
      reportStream.Flush();
      pkg.Close();
  
      return reportStream;
  }
  </code></pre>
  
  <p>PS: When I convert MemoryStream to a file, I got a corrupted file. Thanks!</p>