Tag: C#

C# – Memory stream is not expandable

This COMPLETELY blew my mind!

I had the following code:-


using (MemoryStream contentStream = new MemoryStream(mydata))
 {

      using (WordprocessingDocument myDoc = WordprocessingDocument.Open(contentStream, true))
      {

           MainDocumentPart mainPart = myDoc.MainDocumentPart;

           // Do some stuff

         mainPart.Document.Save();
           myDoc.Close();

      }

}

On mainPart.Document.Save I received the error “memory stream is not expandable”.

I was really confused until I found this post

https://www.codeproject.com/Questions/325125/memory-stream-can-not-be-expendable

If you include your buffer into the constructor then the stream is not extendable. See below:-

// This CANNOT be extended
MemoryStream stream = new MemoryStream(data);

// This CAN be extended
MemoryStream stream = MemoryStream();
stream.Write(data, 0, data.Length);

So in my case I needed to do the following:-


using (MemoryStream contentStream = new MemoryStream())
{
   contentStream.Write(mydata, 0, mydata.Length);
}

Then everything was fine. So beware!