BinaryReader. This C# class handles binary files. A binary file may have thousands of integers stored in it, or another simple data type. Many files can be treated as binary.
File details. If you do not have a binary file you are trying to open already, you can create one using the BinaryWriter type. BinaryReader makes using binary data easier.
Example. Here we open the same binary file and then read in the bytes. BinaryReader here provides some useful properties. When you run the next program, you will see all the ints recovered.
Note We see that BinaryReader receives a FileStream. This is returned by File.Open.
using System;
using System.IO;
class Program
{
static void Main()
{
R();
}
static void R()
{
// 1.
using (BinaryReader b = new BinaryReader(
File.Open("file.bin", FileMode.Open)))
{
// 2.// Position and length variables.
int pos = 0;
// 2A.// Use BaseStream.
int length = (int)b.BaseStream.Length;
while (pos < length)
{
// 3.// Read integer.
int v = b.ReadInt32();
Console.WriteLine(v);
// 4.// Advance our position variable.
pos += sizeof(int);
}
}
}
}1
4
6
7
11
55
777
23
266
44
82
93
Performance. Most programs read in much more data than they write. I found BinaryReader substantially faster than using plain text.
Info Looking into PeekChar indicates that it performs a separate read each time it is called.
Tip This can easily multiply the time required for the BinaryReader. PeekChar should thus be avoided.
using (BinaryReader b = new BinaryReader(File.Open("file.bin", FileMode.Open)))
{
// Do not do this.
while (b.PeekChar() != -1)
{
int v = b.ReadInt32();
}
}
Encoding. Sometimes you can fix an encoding problem by specifying Encoding.ASCII to File.Open. I do not understand why this works but it solved one of my problems.
//// If all else fails, specify Encoding.ASCII to your File.Open call.//
using (BinaryReader b = new BinaryReader(
File.Open("file.bin", FileMode.Open, Encoding.ASCII)))
{
// ...
}
Summary. This C# class is effective for reading binary files. Binary files have great advantages for performance, but they tend not to be standard and can be difficult to work with.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 18, 2023 (simplify).