I have one method that receives a Stream to write on it using a BinaryWriter. But when I dispose this BinaryWriter it also closes the stream. Can I leave it undisposed so I can leave my stream open?
Just do not call Dispose, use Flush instead, its safe.
BinaryWriter
does not call Dispose
in Finalize
like FileStream
does. This behavior implies that BinaryWriter.Dispose
is optional. –
Presidium As of .NET 4.5, the BinaryWriter class has a new constructor that takes a boolean parameter to indicate whether to leave the stream open or not.
Ref: http://msdn.microsoft.com/en-us/library/gg712841.aspx
public BinaryWriter(
Stream output,
Encoding encoding,
bool leaveOpen
)
In the case of BinaryWriter
, that isn't a direct option (although some stream wrappers do allow you to control this, for example GZipStream
etc).
Jon has a NonClosingStreamWrapper in MiscUtil which should work: you wrap your stream in the non-closing wrapper, and give the wrapper to BinaryWriter
. This essentially passes through everything except Close()
and Dispose()
.
BinaryWriter
; it writes values to a stream and tells the stream when it is finished. Care to expand on what you have in mind? It is certainly a lot less hacky than not disposing something that is IDisposable on the grounds that you peeked at the implementation and decided to overrule it... –
Communize Just do not call Dispose, use Flush instead, its safe.
BinaryWriter
does not call Dispose
in Finalize
like FileStream
does. This behavior implies that BinaryWriter.Dispose
is optional. –
Presidium The protected BinaryWriter.Dispose(bool) method is virtual, and all it does is closes the stream (you can check that it is true in Reflector). -This method is called by the Dispose() method.
You can simply inherit a class from the BinaryWriter and override the Dispose(bool) method to do nothing, or something else alltogether.
© 2022 - 2024 — McMap. All rights reserved.