Write to the stream as if it were a file, but actually write to the object

I am trying to write a stream in RAM instead of a file. I tried to do 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 supposedly wrote to it, it says: "Length =" stream.Length "throws an exception like" System.ObjectDisposedException "

+5
source share
5 answers

You call stream.Close()that exactly matches the call Dispose()in the stream.

Just delete this line of code and everything will be fine. Basically, you need to leave it MemoryStreamopen when it returns.

, , , reset . , :

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

, , Dispose() ( stream.Close()), , , /data back out.

+3

, :

using (Stream stream = new MemoryStream()) {
  BinaryFormatter bFormatter = new BinaryFormatter();
  bFormatter.Serialize(stream, objectToSerialize);
  return stream.ToArray();
}
+5

stream.Close( IDisposable.Dispose()), .

, stream.Position = 0;

, , . using - .

0

, stream.Close(); .

0

You get an exception because you are calling Close(). From MSDN: Stream Class

Closes the current stream and frees up any resources (such as sockets and file descriptors) associated with the current stream.

You can simply delete stream.Close();.

0
source

All Articles