Search code examples
c#binarywriter

Do you have to flush your BinaryWriter data


In C# I am using BinaryWriter like this:

BinaryWriter br = new BinaryWriter(myPipe);
var bytes = new byte[5];
br.Write(bytes);
br.Flush();

https://msdn.microsoft.com/de-de/library/system.io.binarywriter.flush(v=vs.110).aspx mentions you should use flush your binary writer.

However I noticed that the data already gets send as soon as br.Write is called and I see no need to call br.Flush?

I am wondering if I can remove that 1 (unnecessary) line of code: br.Flush() or if there is more to it?


Solution

  • That entirely depends on the stream that is used. Flushing a stream means that any buffered data which has not been written yet will be written during the flush. So if the stream you use does not buffer any data, you will not see any difference. If you do not flush the stream it will get flushed the moment you close it.

    The documentation you mentionted only states that:

    All derived classes should override Flush to ensure that all buffered data is sent to the stream.

    Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or Close. Setting AutoFlush to true means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters.