一个优雅的方式来BinaryReader在消费(一的所有字节)?字节、优雅、方式、BinaryReader

由网友(大姨父管好你媳妇)分享简介:有一种优雅的模仿 StreamReader.ReadToEnd 方法 BinaryReader在?也许是为了把所有的字节到字节数组?Is there an elegant to emulate the StreamReader.ReadToEnd method with BinaryReader? Perhaps t...

有一种优雅的模仿 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);

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

}
阅读全文

相关推荐

最新文章