Search code examples
c#.netstreamstreamreaderbinaryreader

An elegant way to consume (all bytes of a) BinaryReader?


Is there an elegant to emulate the StreamReader.ReadToEnd method with BinaryReader? Perhaps to put all the bytes into a byte array?

I do this:

read1.ReadBytes((int)read1.BaseStream.Length);

...but there must be a better way.


Solution

  • Original Answer (Read Update Below!)

    Simply do:

    byte[] allData = read1.ReadBytes(int.MaxValue);
    

    The documentation says that it will read all bytes until the end of the stream is reached.


    Update

    Although this seems elegant, and the documentation seems to indicate that this would work, the actual implementation (checked in .NET 2, 3.5, and 4) allocates a full-size byte array for the data, which will probably cause an OutOfMemoryException on a 32-bit system.

    Therefore, I would say that actually there isn't an elegant way.

    Instead, I would recommend the following variation of @iano's answer. This variant doesn't rely on .NET 4:
    Create an extension method for BinaryReader (or Stream, the code is the same for either).

    public static byte[] ReadAllBytes(this BinaryReader reader)
    {
        const int bufferSize = 4096;
        using (var ms = new MemoryStream())
        {
            byte[] buffer = new byte[bufferSize];
            int count;
            while ((count = reader.Read(buffer, 0, buffer.Length)) != 0)
                ms.Write(buffer, 0, count);
            return ms.ToArray();
        }
        
    }