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.
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.
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With