c# - 使用 Stream.Read() 与 BinaryReader.Read() 处理二进制流

标签 c# .net stream

在处理二进制流(即 byte[] 数组)时,使用 BinaryReaderBinaryWriter 的要点似乎是简化读取/从流中写入原始数据类型,使用 ReadBoolean() 等方法并考虑编码。这是整个故事吗?如果直接使用 Stream 而不使用 BinaryReader/BinaryWriter,是否存在固有优势或劣势?大多数方法,如 Read(),在两个类中似乎是相同的,我猜它们在底层的工作方式相同。

考虑一个以两种不同方式处理二进制文件的简单示例(编辑:我意识到这种方式无效并且可以使用缓冲区,这只是一个示例):

// Using FileStream directly
using (FileStream stream = new FileStream("file.dat", FileMode.Open))
{
    // Read bytes from stream and interpret them as ints
    int value = 0;
    while ((value = stream.ReadByte()) != -1)
    {
        Console.WriteLine(value);
    }
}


// Using BinaryReader
using (BinaryReader reader = new BinaryReader(FileStream fs = new FileStream("file.dat", FileMode.Open)))
{
    // Read bytes and interpret them as ints
    byte value = 0;    
    while (reader.BaseStream.Position < reader.BaseStream.Length)
    {
        value = reader.ReadByte();
        Console.WriteLine(Convert.ToInt32(value));
    }
}

输出将是相同的,但内部发生了什么(例如,从操作系统的角度来看)?一般而言,使用哪种实现方式重要吗?如果您不需要它们提供的额外方法,那么使用 BinaryReader/BinaryWriter 有什么意义吗? 对于这种特定情况,MSDN 在 Stream.ReadByte() 方面这样说:

The default implementation on Stream creates a new single-byte array and then calls Read. While this is formally correct, it is inefficient.

使用 GC.GetTotalMemory(),第一种方法似乎分配的空间是第二种方法的 2 倍,但据我所知,如果更通用的 Stream使用 .Read() 方法(例如,使用缓冲区读取 block )。不过,在我看来,这些方法/接口(interface)可以很容易地统一起来......

最佳答案

不,这两种方法之间没有主要区别。额外的阅读器增加了一些缓冲,所以你不应该混合使用它们。但不要指望有任何显着的性能差异,这完全取决于实际的 I/O。

所以,

  • 当你(只有)byte[] 可以移动时使用流。在许多流媒体场景中很常见。
  • 当您有任何其他基本类型(包括简单的 byte)数据要处理时,请使用 BinaryWriter 和 BinaryReader。它们的主要目的是将内置框架类型转换为 byte[]

关于c# - 使用 Stream.Read() 与 BinaryReader.Read() 处理二进制流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17043631/

相关文章:

c# - WPF 的自动完成组合框

c# - 使用 String.IsNullOrEmpty(string) 和 Nhibernate 创建动态 Linq 表达式

python - 如何在Python3中将异步生成器流转换为类似文件的对象?

c# - 如何设计一个 WPF 依赖属性来支持图像路径?

dart - 在 Dart 中保存流的最后一个发射值

python - Python 中高效的时间限制队列?

c# - 使用不同的兼容类型覆盖属性

c# - 在 SQL Server/LINQ to SQL 中查询 ae 匹配 æ

c# - 为什么表单中的表单在 Internet Explorer 中不起作用

c# - 如何找到事件 app.config 文件的路径?