Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to a stream as if it were a file, but really write to an object

I am trying write a stream to the ram instead of a file. I tried doing this:

Stream stream = new MemoryStream();
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, objectToSerialize);
stream.Close();
return stream;

But when I look at the stream after I have supposedly written to it it is saying "Length = 'stream.Length' threw an exception of type 'System.ObjectDisposedException'"

like image 298
Simon The Cat Avatar asked Sep 02 '11 23:09

Simon The Cat


2 Answers

Don't close the stream before getting the data, and don't return the stream but the content of the stream:

using (Stream stream = new MemoryStream()) {
  BinaryFormatter bFormatter = new BinaryFormatter();
  bFormatter.Serialize(stream, objectToSerialize);
  return stream.ToArray();
}
like image 132
Guffa Avatar answered Nov 17 '22 01:11

Guffa


You're calling stream.Close(), which is exactly the same as calling Dispose() on the stream.

Just remove that line of code, and you should be fine. Basically, you need to leave the MemoryStream open when it's returned.

On a different note, depending on what you're going to do, you may also want to reset the stream's position. I suspect you'll want:

Stream stream = new MemoryStream();
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, objectToSerialize);
stream.Position = 0;
return stream;

This works the same as your code, but does not Dispose() the stream (since it's no longer calling stream.Close()), and also resets it to the start position, which is often required if you want to read the object/data back out.

like image 3
Reed Copsey Avatar answered Nov 17 '22 01:11

Reed Copsey