views:

28

answers:

2

I need to read a certain amount of short (int16) data points from a binary file, starting at a specific position. Thanks!

+4  A: 

You can simply call the Seek method on the Stream that you pass to BinaryReader to the position in the file you want to start reading from.

Then, once you pass the stream to BinaryReader, you can call the ReadInt16 method as many times as you need to.

casperOne
Include code or someone else will.
xcud
+1  A: 

Something like this should do it for you:

private IEnumerable<Int16> getShorts(string fileName, int start, int count)
using(var stream = File.OpenRead(fileName))
{
   stream.Seek(start);
   var reader = new BinaryReader(stream);
   var list = new List<int16>(count);
   for(var i = 0;i<count;i++)
   {
      list.Add(reader.ReadInt16());
   }
}

which is basically what CAsper wrote just in code

Rune FS
Do I have to multiply start by 2 to accommodate for the file consisting of 2-byte values?
mikeh
@mikeh, `Seek` just seeks a given number of bytes. So it really depends what `start` means.
Matthew Flaschen
start in this example is the byte u wish use as start position. If you'd rather give the short to start Reading from, the you Can simply do .Seek(start*2)
Rune FS