是否有一个优雅的方法来模仿BinaryReader
的StreamReader.ReadToEnd
方法?也许把所有字节放入字节数组?
我这样做:
read1.ReadBytes((int)read1.BaseStream.Length);
...但一定有更好的办法.
是否有一个优雅的方法来模仿BinaryReader
的StreamReader.ReadToEnd
方法?也许把所有字节放入字节数组?
我这样做:
read1.ReadBytes((int)read1.BaseStream.Length);
...但一定有更好的办法.
只需执行以下操作:
byte[] allData = read1.ReadBytes(int.MaxValue);
documentation表示它将读取所有字节,直到到达流的末尾.
尽管这看起来很优雅,文档似乎表明这将会起作用,但实际的implementation(在.NET2、3.5和4中判断)为数据分配了一个完整大小的字节数组,这可能会在32位系统上导致OutOfMemoryException
.
因此,我会说实际上是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();
}
}