Why a BinaryWriter closes the outer Stream on disposal, and how to prevent that? (.NET C#)

Jader Dias picture Jader Dias · Jul 5, 2009 · Viewed 8.7k times · Source

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?

Answer

Dave Van den Eynde picture Dave Van den Eynde · Aug 21, 2012

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
)