An elegant way to consume (all bytes of a) BinaryReader?(使用(a)BinaryReader 的所有字节的优雅方式?)
问题描述
是否有一种优雅的方法可以用 BinaryReader 模拟 StreamReader.ReadToEnd 方法?也许将所有字节放入一个字节数组?
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);
文档 说它将读取所有字节,直到到达流末尾.
The documentation says that it will read all bytes until the end of the stream is reached.
虽然这看起来很优雅,并且文档似乎表明这会起作用,但实际的实现(在 .NET 2、3.5 和 4 中检查)为数据,这可能会在 32 位系统上导致 OutOfMemoryException.
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.
因此,我会说实际上没有一种优雅的方式.
相反,我会推荐@iano 答案的以下变体.此变体不依赖于 .NET 4:
为BinaryReader(或Stream,两者的代码相同)创建一个扩展方法.
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();
}
}
这篇关于使用(a)BinaryReader 的所有字节的优雅方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用(a)BinaryReader 的所有字节的优雅方式?
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
