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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s