Reader Level:
ARTICLE

Read a binary file in C#

Posted by Mahesh Chand Articles | Files, Directory, IO July 12, 2012
How to read a binary file in C# and .NET.
  • 0
  • 0
  • 12406
Download Files:
 

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();

Sample 

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

public class BinaryReadWriteClass
{
    public void WriteBinary()
    {
        try
        {
            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 
                binWriter.Write(authorName);
                // Write string 
                // Write integer
                binWriter.Write(age);
                binWriter.Write(bookTitle);
                // Write boolean
                binWriter.Write(mvp);
                // Write double 
                binWriter.Write(price);
            }              
            Console.WriteLine("Data Written!");
            Console.WriteLine();
        }
        catch (IOException ioexp)
        {
            Console.WriteLine("Error: {0}", ioexp.Message);
        }
    }
}

COMMENT USING

Trending up