BinaryWriter, don't close stream

  • Thread starter Thread starter Peter Morris
  • Start date Start date
P

Peter Morris

Can I use a BinaryWriter without it closing the underlying stream?

I want to save information to a MemoryStream using a BinaryWriter but I want
to dispose of the BinaryWriter and keep the MemoryStream in case I wish to
reload information from the MemoryStream using BinaryReader.




Thanks

Pete
 
Peter,

No, you can't, but you can get the contents of the MemoryStream before
the BinaryWriter is finished by calling ToArray on the MemoryStream. You
can then pass this to a new MemoryStream when you want to use it in a
BinaryReader again.
 
Hi,

did you try it?

IIRC Close close the underlined stream. but as you are using a MemoryStream,
well "closing" it has not too much sense.

I would give it a try and post back if you have any problem.
 
Can I use a BinaryWriter without it closing the underlying stream?

I want to save information to a MemoryStream using a BinaryWriter but I want
to dispose of the BinaryWriter and keep the MemoryStream in case I wish to
reload information from the MemoryStream using BinaryReader.


What I've done in the past is to create a proxy Stream class that does
nothing in its Close method, and just forwards all other method calls
to the stream it wraps. Then use it something like

new BinaryWriter(new NonClosingStream(yourActualStream))


Mattias
 
Jon provides such a stream in his "misc utils" library:

http://www.yoda.arachsys.com/csharp/miscutil/

It might not appear on the write-up, but I'm pretty sure it is
there... NonClosingStream or some-such; essentially acts as a
"decorator" for a stream and ignores Close() and Dispose() [it might
call Flush() instead, I can't recall]

Marc
 
My problem is that I want a MyClass.SaveToStream

but as the stream is passed to me I have no (right) to close it. This is
because I have no knowledge of what the application wants to do with the
stream. For example, the app might save 4 objects to the same stream but
the first object will close the stream. It's a bit silly really isn't it
:-) Anyway, I just changed it to

SaveToStream(BinaryWriter writer);



Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top