Search code examples
openxmlopenxml-sdk

How to modify a DocX file and save to a different location with OpenXML SDK?


I want to use OpenXML SDK 2.0 to do the following:

  1. Open A.docx
  2. Modify the document
  3. Save the modified document as B.docx

A & B would be parameters to a method and they could be the same. Assuming they are not the same, A should not be modified at all.

I cannot see a "SaveAs" method, in fact `WordprocessingDocument" class doesn't really seem to support concept of file location.

How should I do this?


Solution

  • I use a memory stream and pass it to the WordprocessingDocument.Open method. After I'm done changing the document, I just write the bytes to the destination:

    var source = File.ReadAllBytes(filename);
    using (var ms = new MemoryStream()) {
        ms.Write(source, 0, source.Length);
        /* settings defined elsewhere */
        using (var doc = WordprocessingDocument.Open(ms, true, settings)) {
            /* do something to the doc */
        }
        /* used in File.WriteAllBytes elsewhere */
        return ms.ToArray();
    }