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'"
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With