C# BinaryReader Tutorial with Programming Examples and Codes

In this chapter you will learn:
  • What is BinaryReader Class in C#?
  • How to read binary file using this class?
  • Programming Examples and Codes.

What is BinaryReader Class in C#?

If you have bin file stored in your PC and you want to read them then BinaryReader may help you lot. BinaryReader class is used to reading binary files. A binary file stored data in different layout that is more efficient for machine but not convenient for human. BinaryReader makes this job simpler and show you exact data stored in bin file.

Notes:
  1. BinaryReader handles Binary (.bin) files.
  2. It reads primitive data types as binary values in a specific encoding.
  3. BinaryReader class provides methods that simplify reading primitive data types from stream.

How to read binary file using BinaryReader Class?

For reading binary file, you need to create binary file first using BinaryWriter Class.
 

Create Binary File using BinaryWriter Class

Programming Example and code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace BinaryReader_Class
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteBinaryFile();
            ReadBinaryFile();
            Console.ReadKey();
        }
        static void WriteBinaryFile()
        {
            using (BinaryWriter writer = new BinaryWriter(File.Open("D:\\binaryfile.bin", FileMode.Create)))
            {
                //Writting Error Log
                writer.Write("0x80234400");
                writer.Write("Windows Explorer Has Stopped Working");
                writer.Write(true);
            }
        }
        static void ReadBinaryFile()
        {
            using (BinaryReader reader = new BinaryReader(File.Open("D:\\binaryfile.bin", FileMode.Open)))
            {
                Console.WriteLine("Error Code : " + reader.ReadString());
                Console.WriteLine("Message : " + reader.ReadString());
                Console.WriteLine("Restart Explorer : " + reader.ReadBoolean());
            }
        }
    }
}

Output
Error Code : 0x80234400
Message : Windows Explorer Has Stopped Working
Restart Explorer : true

Explanation

In the above example I have created 2 methods WriteBinaryFile() and ReadBinaryFile(). WriteBinaryFile() method stores some information in D:\binaryfile.bin file and ReadBinaryFile() methods read data from bin file and displays on console screen.

Summary

In this tutorial you learned BinaryReader class with complete programming example. In the next chapter you will learn StringWriter class.

 

Share your thought