一个优雅的方式来BinaryReader在消费(一的所有字节)? [英] An elegant way to consume (all bytes of a) BinaryReader?

查看:179
本文介绍了一个优雅的方式来BinaryReader在消费(一的所有字节)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种优雅的模仿 StreamReader.ReadToEnd 方法 BinaryReader在?也许是为了把所有的字节到字节数组?

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

我这样做:

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

...但必须有一个更好的办法。

...but there must be a better way.

推荐答案

简单地做:

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

的<一个href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.readbytes.aspx">documentation说,它将读取的所有字节,直到流的末尾为止。

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

虽然这看起来优雅,和文档似乎表明,这将工作,实际的实施(检查在.NET 2,3.5和4)用于分配一个全尺寸的字节数组数据,这可能会导致一个 OutOfMemoryException异常在32位系统。

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.

相反,我会推荐@ iano的回答下面的变化。这种变异并不依赖于.NET 4:
创建 BinaryReader在的扩展方法(或中,code是相同的两种)。

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();
    }

}

这篇关于一个优雅的方式来BinaryReader在消费(一的所有字节)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆