是否有一个优雅的方法来模仿BinaryReaderStreamReader.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();
    }
    
}

.net相关问答推荐

条带连接支付—引发异常

如何将 select 语句详细信息提取到不同的方法中仍然保持Eager 加载?

.Net MAUI Android 无法与 API localhost 对话

.NET 4.5 项目未在 Visual Studio 2022 中编译

异步总是 WaitingForActivation

在目录中创建应用程序快捷方式

比较 C# 中的字符串和对象

将屏幕捕获为位图

如何在 C# 中打开 Excel 文件?

从 Web.Config 中的邮箱友好显示名称存储 Smtp

在 C# 中转义命令行参数

参数命名:文件名还是文件名?

WCF反序列化如何在不调用构造函数的情况下实例化对象?

为什么 System.Timers.Timer 能在 GC 中存活,而 System.Threading.Timer 不能?

自定义属性的构造函数何时运行?

在 .NET 中计算目录大小的最佳方法是什么?

在 C#/.NET 中组合路径和文件名的最佳方法是什么?

有没有一种简单的方法来判断 .NET Framework 版本?

在类型 c# 上切换大小写

无法添加对 dll 的引用