Sunday, March 10, 2013

MemoryStream exception–Memory stream is not expandable

Just got hit by this exception.

I was creating a memory stream from bytes that I had read from a file:

var fileBytes = File.ReadAllBytes(filePath);
MemoryStream ms = new MemoryStream(fileBytes, true);

The memory stream was then being used in a bunch of operations that could add data and when it did, it caused the “Memory stream is not expandable” exception to be thrown.

Found out that its because of the constructor that I was using. Because I was providing memory-stream the actual bytes, it was creating the memory stream as a non-expandable one. Instead, if you construct it and then write to it, the memory stream has no such restriction and it can expand.

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

1 comment:

toakeley said...

Various constructors