title: .Net C# DocX librairy : how to serialize a DocX document?
body: <p>When using the DocX librairy, i am generating the docx document on server then download it.</p>
  
  <p>For that, i need to convert my document in an array of bytes.</p>
  
  <p>To do that, i was previousloy saving the document as a physical file like this :</p>
  
  <pre><code>// Save all changes to this document.
  document.SaveAs(GENERATED_DOCX_LOCATION);
  
  return System.IO.File.ReadAllBytes(GENERATED_DOCX_LOCATION);
  </code></pre>
  
  <p>but i would rather not do that. Is it possible to serialize this object to download it without saving it physically ?</p>
  
  <p>I already tried that :</p>
  
  <pre><code>private byte[] ObjectToByteArray(object obj)
  {
      if (obj == null)
          return null;
      BinaryFormatter bf = new BinaryFormatter();
      using (MemoryStream ms = new MemoryStream())
      {
          bf.Serialize(ms, obj);
          return ms.ToArray();
      }
  }
  </code></pre>
  
  <p>With :</p>
  
  <pre><code>return this.ObjectToByteArray(document);
  </code></pre>
  
  <p>But obviously, DocX doesn't implement ISerializable.</p>
  
  <p><strong>EDIT</strong> : the code below doesn't work either </p>
  
  <pre><code>byte[] byteArray = null;
  using (var stream = new MemoryStream())
  {
      document.SaveAs(stream);
      byteArray = stream.ToArray();
  }
  return byteArray;
  </code></pre>