Read binary file in C# from specific position

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.

Here:
This example gets the 50000th byte to the 51999th byte and iterates through them.

Note:
The BinaryReader class is used. The program opens the binary file with BinaryReader here. It uses the “perls.bin” file.
File.Open

C# program that seeks in Main method

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.

Seek:
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.

4.9/5 - (38 votes)