0

I have a memorystream reading a specific part of my data. From the binary I want one ReadInt32 value from position 5-8. How do I achieve this in:

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

  somebyte1
  somebyte2
  somebyte3

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

}

2 Answers2

0

Move the base stream to the position you want to read from:

stream.Seek(4, SeekOrigin.Begin);

using (var reader = new BinaryReader(stream))
{
    int v = reader.ReadInt32;
}
Gusman
  • 14,905
  • 2
  • 34
  • 50
0

In .NET there are stream types that are seekable and types that don't allow seek. This is indicated by the CanSeek property. If your stream allows seek (and a MemoryStream does), you can just move the current position and read the data. If the stream does not allow seek, your only choice is to read and discard the data until you reach the stream position where your desired data is at. So the generalized solution to your problem would be:

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();
}
Sefe
  • 13,731
  • 5
  • 42
  • 55