C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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 "Codex.bin" file.
File.OpenC# program that seeks in Main method
using System;
using System.IO;
class Program
{
static void Main()
{
// 1.
// Open as binary file.
using (BinaryReader b = new BinaryReader(File.Open("Codex.bin",
FileMode.Open)))
{
// 2.
// Important variables:
int length = (int)b.BaseStream.Length;
int pos = 50000;
int required = 2000;
int count = 0;
// 3.
// Seek the required index.
b.BaseStream.Seek(pos, SeekOrigin.Begin);
// 4.
// Slow loop through the bytes.
while (pos < length && count < required)
{
byte y = b.ReadByte();
// 5.
// Increment the variables.
pos++;
count++;
}
}
}
}
Seek: We call Seek on the BaseStream and move the position to 50000 bytes. It looks through each byte.
Warning: The above code can slow down IO. It apparently requires each byte to be read separately off the disk.
Here: The example opens the same binary file. We start at the same index in the file as the previous example (the 50000th byte).
Info: BinaryReader itself doesn't provide Seek, but you can use BaseStream with no damage.
And: It calls ReadBytes. This reads in the 2000 required bytes. These are stored in the byte array.
Note: If there aren't enough bytes left, the ReadBytes method does not throw exceptions.
C# program that uses Seek and ReadBytes
using System;
using System.IO;
class Program
{
static void Main()
{
// 1.
// Open file with a BinaryReader.
using (BinaryReader b = new BinaryReader(File.Open("Codex.bin",
FileMode.Open)))
{
// 2.
// Variables for our position.
int pos = 50000;
int required = 2000;
// 3.
// Seek to our required position.
b.BaseStream.Seek(pos, SeekOrigin.Begin);
// 4.
// Read the next 2000 bytes.
byte[] by = b.ReadBytes(required);
}
}
}
BinaryReader.ReadBytes: Reads count bytes from the current stream into a byte array and advances the current position by count bytes.
ReadBytes: Microsoft DocsBinaryReader.Read: Reads count bytes from the stream with index as the starting point in the byte array.
Read: Microsoft DocsNote: This may occur because Windows doesn't buffer the single byte reads well. Also, there are different layers of code here.
Benchmark notes for Seek
Bytes read: 20000
File size: 2.94 MB
Start position: Inclusive random number
Compilation: Release
Iterations: 10000
Seek benchmark results
Read one byte: 2574 ms
Read array: 671 ms
Finally: In my test with a three megabyte file, the amount of time executing the Seek wasn't significant.