C# BinaryReader

In c#, BinaryReader is a class of System.IO namespace and it is useful to read binary information from the stream with a particular encoding. By default, the BinaryReader will use UTF-8 Encoding unless we specify other encodings.

 

Now, we will see how to use BinaryReader class in c# to read binary information from the file with examples.

C# BinaryReader Example

Following is the example of writing a text to the file in binary format and retrieving that binary information from the file using BinaryReader object in c#.

 

using System;

using System.IO;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            string fpath = @"D:\Test.txt";

            // Writing values to file

            if (File.Exists(fpath))

            {

                File.Delete(fpath);

            }

            using (BinaryWriter bw = new BinaryWriter(File.Open(fpath, FileMode.Create)))

            {

                bw.Write(1.25);

                bw.Write("Welcome to Tutlane");

                bw.Write(10);

                bw.Write(true);

                bw.Write("test");

            }

            // Reading Values by creating BinaryReader instance

            using (BinaryReader br = new BinaryReader(File.Open(fpath, FileMode.Open)))

            {

                Console.WriteLine(br.ReadDouble());

                Console.WriteLine(br.ReadString());

                Console.WriteLine(br.ReadInt32());

                Console.WriteLine(br.ReadBoolean());

                Console.WriteLine(br.ReadString());

            }

            Console.ReadLine();

        }

    }

}

If you observe the above example, we imported a System.IO namespace in our example to access BinaryWriter & BinaryReader objects to create, open and read text from the given file.

 

When we execute the above example, it will create a “Test.txt” file in D drive and read a text from the created file and return the result like as shown below.

 

C# BinaryReader Example Result

 

This is how we can use BinaryReader class in c# to read the binary information from a file in the file system.

 

PREVIOUS

C# BinaryWriter
 

NEXT

C# FileInfo  
 

Topics Covered