A Word document that arrives as a stream - an upload body, a blob-storage download, or an in-memory buffer - can be loaded and saved without writing a temporary file to disk. The code example above reads a .docx from any readable stream asynchronously, saves the result into a MemoryStream, and extracts the final bytes as an array.
5-Step Guide to Loading and Saving a Word Document in Memory
- Install IronWord via NuGet
- Open or receive a readable stream containing .docx bytes
- Load the document asynchronously from the stream with
WordDocument.LoadAsync - Save the document into a new
MemoryStreamwithSaveAsync - Extract the byte array with
ToArrayfor downstream use
Code Explanation
WordDocument.LoadAsync(Stream) reads the document from the stream's current position to the end; WordDocument(Stream) is the synchronous equivalent. SaveAsync(Stream) writes the serialized .docx bytes into the target stream at its current position; Save(Stream) is the synchronous equivalent. The caller owns both streams - IronWord does not close them, which is why both carry a using declaration. A reused output stream must be emptied with SetLength(0) before saving, because the save does not truncate it. ToArray() reads the entire backing buffer regardless of the stream's position, so no rewind is needed to obtain the bytes after saving.