从特定位置的二进制文件中读取 Int32

Read Int32 from binary at specific position

我有一个内存流读取我数据的特定部分。从二进制文件中,我想要一个来自位置 5-8 的 ReadInt32 值。我该如何实现:

using (var reader = new BinaryReader(stream))
{

  somebyte1
  somebyte2
  somebyte3

  //get only this value
  int v = reader.ReadInt32;

}

将基本流移动到您要读取的位置:

stream.Seek(4, SeekOrigin.Begin);

using (var reader = new BinaryReader(stream))
{
    int v = reader.ReadInt32;
}

在 .NET 中,存在可搜索的流类型和不允许搜索的类型。这由 CanSeek 属性 表示。如果您的流允许搜索(并且 MemoryStream 允许),您可以只移动当前位置并读取数据。如果流不允许查找,您唯一的选择是读取并丢弃数据,直到到达所需数据所在的流位置。因此,您的问题的一般解决方案是:

const int targetPosition = 4;
BinaryReader reader = new BinaryReader(stream);
using (reader) {
    if (stream.CanSeek) {
        stream.Position = targetPosition;
    }
    else {
        reader.ReadBytes(targetPosition);
    }
    int result = reader.ReadInt32();
}