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'”
You’re calling
stream.Close(), which is exactly the same as callingDispose()on the stream.Just remove that line of code, and you should be fine. Basically, you need to leave the
MemoryStreamopen 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:
This works the same as your code, but does not
Dispose()the stream (since it’s no longer callingstream.Close()), and also resets it to the start position, which is often required if you want to read the object/data back out.