Search code examples
c#asp.net-mvcwordprocessingml

Random error Memory stream is not expandable


I was updating word document content using following code which was randomly throwing error Memory stream is not expandable:

MemoryStream TemplateFileMS = new MemoryStream(fileBytes);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(TemplateFileMS, true))
//...
// some code
//...
wordDoc.MainDocumentPart.Document.Save(); // Exception here

After changing the code to below, the error is not occurring.

MemoryStream TemplateFileMS = new MemoryStream(0);
TemplateFileMS.Write(fileBytes, 0, fileBytes.Length);

So I am able to fix the issue. But I didn't see the above error in my dev environment on Azure App Service but in the production Azure App Service I was getting the Memory is not expandable error randomly.

Is it related to the number of bytes/updates that is making difference here? e.g. while testing I make only few updates but in some scenarios there are more updates which requires extra memory than the set capacity.

I tried adding more updates to the document but I was not able to reproduce this error with previous code.

Thank you!


Solution

  • Normally, you'd only initialize a MemoryStream from a byte[] to read values from an existing buffer. But you are writing to the stream. That means you either need to let the MemoryStream manage the buffers itself (by not giving it one), or the buffer you give it needs to be big enough. In most cases the first option is simpler. It is complaining because you have given it a buffer that turned out to be too small, but it can't resize it because you defined the buffer externally (rather than letting the MemoryStream have control).