Open XML: How to save an existing WordprocessingDocument to MemoryStream?

45 views Asked by At

In my class, I receive a WordprocessingDocument object as a return from another method. I know the document was created in-memory (MemoryStream).

Now, I need to either get the underlying MemoryStream of this WordprocessingDocument object, or resave it to a new MemoryStream.

I need it as MemoryStream so I can transfer it to our repository.

How can I either access the underlying MemoryStream, or resave the object to a new MemoryStream?

1

There are 1 answers

0
FortyTwo On

You can clone the WordprocessingDocument into a new MemoryStream like this:

static MemoryStream CloneWordprocessingDocument(WordprocessingDocument document)
{
    MemoryStream memStream = new MemoryStream();
    document.Clone(memStream,true);
    memStream.Position = 0;
    return memStream;
}

I tested it with a console project below:

class Program
{
    static void Main()
    {
        WordprocessingDocument wordDocument = WordprocessingDocument.Open("Test.docx", true);

        // Clone the WordprocessingDocument to a MemoryStream
        MemoryStream clonedStream = CloneWordprocessingDocument(wordDocument);

        File.WriteAllBytes("Final.docx", clonedStream.ToArray());
    }

    static MemoryStream CloneWordprocessingDocument(WordprocessingDocument document)
    {
        MemoryStream memStream = new MemoryStream();
        document.Clone(memStream,true);
        memStream.Position = 0;
        return memStream;
    }
}