2

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?

csharpbd
  • 3,786
  • 4
  • 23
  • 32
Shmoopy
  • 5,334
  • 4
  • 36
  • 72

1 Answers1

5

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 :-) )

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • 1
    Also, do this outside of the `using{}` because the repositioning will screw up the bufferedStream beyond usability. – H H Mar 20 '17 at 10:54
  • @HenkHolterman If he doesn't want to write anymore there should be no problem. He `Flush()`ed the `BufferedStream()` so I think it is acceptable to assume the `BufferedStream` won't write anything on `Dispose()`/`Close()` (if there is no new `Write()`)... But yes, the fact that there is a single `Position` (and not a `ReadPosition`/`WritePosition`) can cause "fun" bugs :-) – xanatos Mar 20 '17 at 10:57
  • 1
    @HenkHolterman Other problem: you can't create a `BufferedStream` that doesn't take ownership of the base `Stream`, so by `Close()`/`Dispose()` of the `BufferedStream`, the base stream will be `Close()`... (see [referencesource](https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/bufferedstream.cs#L275))... – xanatos Mar 20 '17 at 10:59
  • @HenkHolterman Or do a `ToArray()`... Both don't require the `Position = 0` – xanatos Mar 20 '17 at 11:01