Seek locates a position in a file. It allows data to be read from a binary file at a certain part. For example, we can read 20,000 bytes from any part of a file. This is useful for certain file formats—particularly binary ones.
Example. To begin our tutorial, we use the Seek method. From databases, you know that Seek is the term for when the data can be instantly retrieved, with an index. Therefore, Seek should be fast.
This example gets the 50000th byte to the 51999th byte and iterates through them.
The BinaryReader class is used. The program opens the binary file with BinaryReader here. It uses the “perls.bin” file.
C# program that seeks in Main method
static void Main()
// Open as binary file.
using (BinaryReader b = new BinaryReader(File.Open("perls.bin",
// Important variables:
int length = (int)b.BaseStream.Length;
int pos = 50000;
int required = 2000;
int count = 0;
// Seek the required index.
// Slow loop through the bytes.
while (pos < length && count < required)
byte y = b.ReadByte();
// Increment the variables.
Variables used in program. Length is the entire length of the file we are reading from. Pos is the index we want to start reading from. Required is the number of bytes we want to read. Count is the number of bytes we have read.
We call Seek on the BaseStream and move the position to 50000 bytes. It looks through each byte.
The above code can slow down IO. It apparently requires each byte to be read separately off the disk. By using arrays, we can improve performance by several times. Next, we look at the version that uses arrays.