Search code examples
c#bufferedstream

BufferedStream Flush() doesn't write to MemoryStream()?


I was trying out BufferedStream over MemoryStream:

using (var ms = new MemoryStream(64))
using (var bs = new BufferedStream(ms, 32))
{
    var buffer = new byte[] { 0xab, 0xab, 0xab, 0xab };
    bs.Write(buffer, 0, buffer.Length);
    bs.Flush();

    var actual = new byte[4];

    int cb = ms.Read(actual, 0, actual.Length);
    Console.WriteLine(cb);
}

It prints 0. I was expecting it to print 4 since I figured bs.Flush() would write the 4 buffered bytes to ms.

Am I using BufferedStream wrong somehow or was my expectation simply wrong?


Solution

  • You must write

    ms.Position = 0;
    int cb = ms.Read(actual, 0, actual.Length);
    

    It is a very common error forgetting to rewind a MemoryStream() after writing to it :-) (let's say that I do it every time :-) )