By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,418 Members | 1,421 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,418 IT Pros & Developers. It's quick & easy.

MemoryStream and BinaryWriter buffering question

P: n/a
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

Nov 16 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
keithv <kv*****@gmail.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.