.Net C# DocX librairy : how to serialize a DocX document?

997 Views Asked by At

When using the DocX librairy, i am generating the docx document on server then download it.

For that, i need to convert my document in an array of bytes.

To do that, i was previousloy saving the document as a physical file like this :

// Save all changes to this document.
document.SaveAs(GENERATED_DOCX_LOCATION);

return System.IO.File.ReadAllBytes(GENERATED_DOCX_LOCATION);

but i would rather not do that. Is it possible to serialize this object to download it without saving it physically ?

I already tried that :

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();
    }
}

With :

return this.ObjectToByteArray(document);

But obviously, DocX doesn't implement ISerializable.

EDIT : the code below doesn't work either

byte[] byteArray = null;
using (var stream = new MemoryStream())
{
    document.SaveAs(stream);
    byteArray = stream.ToArray();
}
return byteArray;
2

There are 2 best solutions below

0
G.Dealmeida On BEST ANSWER

There was no way to do it via the original DocX library.

It's a shame as this library uses a MemoryStream to manupulate the datas.

To solve my problem i simply added a new public readonly property to expose the private MemoryStream variable, then i used this simple code :

Code added in the DocX project :

public MemoryStream DocumentMemoryStream { get { return this.memoryStream; }  } 

Code in my main function :

return document.DocumentMemoryStream.ToArray();
3
Simon Price On

Try this, replace my c:\temp... path with your document location and this will get and write the file for you from the byte array

void Main()
{
    byte[] bytes = System.IO.File.ReadAllBytes(@"C:\temp\test.csv");

    using (var bw = new BinaryWriter(File.Open(@"C:\temp\test2.csv", FileMode.OpenOrCreate)))
    {
        bw.Write(bytes);
        bw.Flush();
    }

}