Simon The Cat
Simon The Cat

Reputation: 654

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'"

Upvotes: 5

Views: 3624

Answers (5)

Guffa
Guffa

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

IAbstract
IAbstract

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

Samich
Samich

Reputation: 30115

It's because you stream.Close(); the object.

Upvotes: 0

Eric J.
Eric J.

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

Reed Copsey
Reed Copsey

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

Related Questions