Reputation: 654
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'"
Upvotes: 5
Views: 3624
Reputation: 700342
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();
}
Upvotes: 5
Reputation: 19881
You are getting the exception because you call Close()
. From MSDN: Stream Class
Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
You should be able to simply remove stream.Close();
.
Upvotes: 0
Reputation: 150108
Don't call stream.Close (or IDisposable.Dispose()) until you're done with the stream.
You probably need to set the stream position back to start stream.Position = 0;
Make sure that you do dispose of the stream when you're done. The using statement is your friend here.
Upvotes: 0
Reputation: 564413
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.
Upvotes: 3