Memorystream Not Expandable: Invalid Operation Exception

There's a little gotcha with the MemoryStream class that I just found out. It has 7 constructors. The default constructor has the stream set as expandable, with an initial capacity of 0. The ctors that take the capacity set the capacity to the param, but also keeps the stream expandable. If, however, you use a ctor with the byte[] param, it initializes the stream with the contents of the buffer, but the stream becomes non-expandable.

So, if you have something like this:

byte[] buffer = File.ReadAllBytes("filaname.docx");

MemoryStream ms = new MemoryStream(buffer);

MemoryStream ms2 = new MemoryStream();

ms2.Write(buffer, 0, buffer.Length);

then, ms will NOT be expandable, ms2 will be. So, if you are modifying the stream and the size may increase, the first ctor will not work, but the second approach will work just fine.


Hope that helps :)


Comments have been disabled for this content.