【问题标题】:Is it possible to detect if BinaryReader.ReadBytes(int) reaches the end of a stream?是否可以检测 BinaryReader.ReadBytes(int) 是否到达流的末尾?
【发布时间】:2020-10-24 14:38:37
【问题描述】:

如果BinaryReader 的大多数读取方法到达流的末尾,它会抛出EndOfStreamException,但奇怪的是ReadBytes 方法不会。但是,如果我仍然想抛出 EndOfStreamException 怎么办?我该如何检测?

我可以使用 BaseStream.Position 属性,但我使用的 steam 不支持搜索,所以这会抛出 NotSupportedException。

【问题讨论】:

    标签: c# io binaryreader


    【解决方案1】:

    我在输入问题时找到了答案。事实证明,如果到达流的末尾,该方法只返回一个较短的数组。所以这就是你可以检测到它的方法:

    byte[] bytes = binaryReader.ReadBytes(someNumber);
    if (bytes.Length != someNumber)
        throw new EndOfStreamException(); // Or do something else.
    

    【讨论】:

      猜你喜欢
      • 2011-12-01
      • 2019-11-12
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多