cabgef
cabgef

Reputation: 1398

How do I read shorts from a binary file starting at position x, for y values?

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

Upvotes: 2

Views: 4102

Answers (2)

Rune FS
Rune FS

Reputation: 21742

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

Upvotes: 4

casperOne
casperOne

Reputation: 74530

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.

Upvotes: 3

Related Questions