MemoryStream and BinaryWriter buffering question

  • Thread starter Thread starter keithv
  • Start date Start date
K

keithv

Hi,

The msdn doc for MemoryStream has two conflicting statements
about accessing a MemoryStream's buffer after it's been closed:

The buffer is still available on a MemoryStream once
the stream has been closed.

But later it says:

Attempting to manipulate a stream after it has been
closed might throw an ObjectDisposedException.

So what's the correct idiom to do write and then extract
binary data from a MemoryStream:

MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(123);
bw.Write("hello, world");
bw.Close(); // should this be flush instead???
byte[] data = ms.ToArray();
ms.Close();

Also, does one typically need to Dispose() a MemoryStream to
free it's internal buffer? (Doesn't bw.Close() call ms.Close()
so it can't free the buffer?)


Thanks,
Keith
 
keithv said:
The msdn doc for MemoryStream has two conflicting statements
about accessing a MemoryStream's buffer after it's been closed:

The buffer is still available on a MemoryStream once
the stream has been closed.
Yup.

But later it says:

Attempting to manipulate a stream after it has been
closed might throw an ObjectDisposedException.

Yup. All of the normal Stream methods will fail if you call them.
So what's the correct idiom to do write and then extract
binary data from a MemoryStream:

Call ToArray after closing the MemoryStream.
Also, does one typically need to Dispose() a MemoryStream to
free it's internal buffer? (Doesn't bw.Close() call ms.Close()
so it can't free the buffer?)

There's no real *need* to close either a MemoryStream or a
BinaryWriter, but I think it's good form to use a using statement to
dispose of both - that way if you change at a later date to use
something that really *does* need disposing, it will fit into the same
code.
 
Back
Top