FileStream stream = new FileStream("test",FileMode.Create);
BufferedStream buff = new BufferedStream(stream, 8);
BinaryWriter writer = new BinaryWriter(buff);
writer.Write(1);
writer.Write(2);
writer.Write(3);
Console.WriteLine(buff.Length);
As I understand content is flushed when it reaches bufer size in this code 8 bytes.
So why buff.Length returns 12 and why data appears in file only if I explicit call Dispose/Close?
The
BufferedStreamworks fine – it doesn’t flush:stream.Lengthis8until it is closed; i.e.The reason that
buff.Lengthis12is because that is the length of the underlying stream. Basically,BufferedStreamjust re-exposes the stream underneath, and to ensure it doesn’t miss the buffered data it adds aFlush()if there is buffered data:Hence:
Note that the
FileStreamcan have its own buffering too