Search code examples
c#arraysbinaryreader

How to point to the particular index of BinaryStream?


I have a byte array consist of 32 bytes. I want to read 4 bytes from index position 16 to 19. How can i point binary reader to start reading from index 16. I am trying these commands

byte[] trace ; // 32 byte array
using (FileStream s = File.OpenRead(filename))
using (BinaryReader r = new BinaryReader(s))
 {
   r.baseStream.Seek(position,SeekOrigin.Begin);
   byte[] by = r.ReadBytes(4);
 }

but i don't know what to put at position?


Solution

  • I think I got it (although your sample in the question is not very clear).

    You have the byte array trace with 32 elements in it and you want to read 4 bytes starting with position 16.

    Assuming that endianness is not a variable, you can use this to read the 4 bytes as an int value or byte array:

    using(var memStream = new MemoryStream(trace)) 
    {
      //position the stream
      using(var reader = new BinaryReader(memStream)
      {
        memStream.Seek(16, SeekOrigin.Begin);
        var intValue = reader.ReadInt32();
    
        memStream.Seek(16, SeekOrigin.Begin);
        //now read a byte array
        var byteArray = reader.ReadBytes(4);
      }
    }