This C# method 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.
Seek()
is useful for certain file formats—particularly binary ones. With Seek we can improve performance and only read data where needed.
Here 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.
byte
to the 51999th byte
and iterates through them.BinaryReader
class
is used. The program opens the binary file with BinaryReader
here. It uses the "perls.bin" file.BaseStream
and move the position to 50000 bytes. It looks through each byte
.byte
to be read separately off the disk.using System; using System.IO; class Program { static void Main() { // Open as binary file. using (BinaryReader b = new BinaryReader(File.Open("perls.bin", FileMode.Open))) { int length = (int)b.BaseStream.Length; int pos = 50000; int required = 2000; int count = 0; // Seek the required index. b.BaseStream.Seek(pos, SeekOrigin.Begin); // Slow loop through the bytes. while (pos < length && count < required) { byte y = b.ReadByte(); pos++; count++; } } } }
We next use the Seek method with arrays of bytes. There are 2 useful methods you can call to read in an array of bytes. They are Read and ReadBytes
.
byte
).BinaryReader
itself doesn't provide Seek, but you can use BaseStream
with no damage.ReadBytes
. This reads in the 2000 required bytes. These are stored in the byte
array.ReadBytes
method does not throw exceptions.using System; using System.IO; class Program { static void Main() { // Open file with BinaryReader. using (BinaryReader b = new BinaryReader(File.Open("perls.bin", FileMode.Open))) { // Variables for our position. int pos = 50000; int required = 2000; // Seek to our required position. b.BaseStream.Seek(pos, SeekOrigin.Begin); // Read the next 2000 bytes. byte[] by = b.ReadBytes(required); } } }
Should we use Seek with ReadBytes
? Here we compare the performance of single byte
reads to array reads. The array example is much faster.
byte
reads well.Bytes read: 20000 File size: 2.94 MB Start position: Inclusive random number Compilation: Release Iterations: 10000Read one byte: 2574 ms Read array: 671 ms
We used the Seek method on the BinaryReader
and FileStream
classes. We measured performance. Using the array read method is far faster than using single bytes.