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();
}