HeartattacK

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 :)

Posted: Aug 25 2008, 02:31 AM by HeartattacK | with 7 comment(s)
Filed under: , ,

Comments

funny wallpaper » Memorystream Not Expandable: Invalid Operation Exception said:

Pingback from  funny wallpaper » Memorystream Not Expandable: Invalid Operation Exception

# August 24, 2008 3:49 PM

Ravi said:

Exactly what I was looking for, thanks.

# October 30, 2008 10:55 AM

AASHISH SHIVHARE said:

What I am finding, you tell exactly same.

# November 10, 2008 3:59 AM

Anbu said:

Thanks for the Information. Exactly i came across the same problem and now it works for me...

# January 13, 2009 6:51 AM

Dennis said:

you made my day, thanks (L) attack

# May 19, 2009 12:19 PM

Nelson said:

Using C#, one of the constructors has a 'writable' parameter.  You can do the following...

MemoryStream ms = new MemoryStream(buffer, true);

The effect is an MemoryStream object that is initialized using the 'buffer' and that can be expanded.

Hope this helps.

# September 20, 2009 2:46 PM

Nelson said:

My mistake -- doesn't work.

The 'writable' parameter seems useless.

# September 20, 2009 2:53 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)