Reader Level:

Read a binary file in C#

By Mahesh Chand on Jul 12, 2012
How to read a binary file in C# and .NET.

The System.IO.BinaryReader class is used to read primitive .NET data types as binary in a specific encoding including ASCII, Unicode, UTF32, UTF7, and UTF8 encoding. 

Create a BinaryReader

The BinaryWriter constructor has overloaded forms to support a stream and encoding.  The following code snippet creates BinaryWriter objects with a stream and character encoding format. 

BinaryReader binReader = new BinaryReader(File.Open(fileName, FileMode.Open)

Encoding ascii = Encoding.ASCII;
BinaryWriter bwEncoder = new BinaryWriter(new FileStream(fileName, FileMode.Create), ascii);

Reading a Binary File

The Read overloaded method is used to write primitive data types to a stream. The Write method can write a Boolean, Byte, Char, Decimal, Double, and Integer data types.  The BinaryReader also provides data type specific methods such as ReadString, ReadInt32 and so on. 

The following code snippet reads various data types using their respective methods.

string authorName = binReader.ReadString();
int age = binReader.ReadInt32();
string bookTitle = binReader.ReadString();
bool mvp = binReader.ReadBoolean();
double price = binReader.ReadDouble();


Here is a complete sample code that creates a binary file and adds data to it.

public class BinaryReadWriteClass
    public void WriteBinary()
            Console.WriteLine("Binary Writer");
            string authorName = "Mahesh Chand";
            int age = 30;
            string bookTitle = "ADO.NET Programming using C#";
            bool mvp = true;
            double price = 54.99;

            string fileName = @"C:\temp\MC.bin";                
            BinaryWriter bwStream = new BinaryWriter(new FileStream(fileName,FileMode.Create));

            Encoding ascii = Encoding.ASCII;
            BinaryWriter bwEncoder = new BinaryWriter(new FileStream(fileName, FileMode.Create), ascii);

            using (BinaryWriter binWriter =
                new BinaryWriter(File.Open(fileName, FileMode.Create)))
                // Write string 
                // Write string 
                // Write integer
                // Write boolean
                // Write double 
            Console.WriteLine("Data Written!");
        catch (IOException ioexp)
            Console.WriteLine("Error: {0}", ioexp.Message);

Mahesh Chand
Mahesh Chand

C# Corner founder, 10-times Microsoft MVP, technical author, and software architect. Mahesh authored his first book, A Programmer’s Guide to ADO.NET in C# with APress at the age of 25. C# Corner is a memb... Read more



JetBrains ReSharper Ultimate
.NET code analysis, refactorings, navigation, unit testing, code coverage and profiling in Visual Studio, a bonus for C++ devs, bundled at 50% off.

Trending up