find and solve || findandsolve.com
Please wait.....

How BinaryReader works in C# with Examples

In the C#, BinaryReader class is used to read binary information from stream. BinaryReader used System.IO namespace and also supports reading string in specific encoding.

Syntax with explanation

We can create an object of BinaryReader in three ways as given below:

BinaryReader <objName> = new BinaryReader(inputStream);
BinaryReader <objName>= new BinaryReader(inputStream, encoding);
BinaryReader <objName>= new BinaryReader(inputStream, encoding, true);

Read() methods of BinaryReader for different types of data like as given below


MethodDescription
Read()It is used to read characters from an underlying stream and it also advances the current position of the stream according to the Encoding used and the specific character being read from the stream.
ReadBoolean() It is used to read the Boolean value from the stream and it also advances the current position of the stream by one byte.

ReadByte() It is used to read the next byte from the current stream and it also advances the current position of the stream by one byte.

ReadChar() It is used to read the next character from the current stream and it also advances the current position of the stream according to the Encoding used and the specific character being read from the stream.

ReadDecimal() It is used to read the decimal value from the current stream and it also advances the current position of the stream by sixteen bytes.

ReadDouble() It is used to read an 8-byte floating-point value from the current stream and advances the current position of the stream by eight bytes.

ReadInt32() It is used to read a 4-byte signed integer from the current stream and also it advances the current position of the stream by four bytes.

ReadString() It is used to read a string from the current stream.


C# BinaryReader Example

using System;  
using System.IO;
namespace BinaryWriterExample
{
  public class Program
    {
       public static void Main(string[] args)
        {
            WriteBinaryFile();
            ReadBinaryFile();
            Console.ReadKey();
        }
        public static void WriteBinaryFile()
        {
            using (BinaryWriter writer = new BinaryWriter(File.Open("d:\\test.dat", FileMode.Create)))
            {
                writer.Write(12.5);
                writer.Write("this is string data");
                writer.Write(true);             }
        }
        public static void ReadBinaryFile()
        {
            using (BinaryReader reader = new BinaryReader(File.Open("d:\\test.dat", FileMode.Open)))
            {
                Console.WriteLine("Double Value : " + reader.ReadDouble());
                Console.WriteLine("String Value : " + reader.ReadString());
                Console.WriteLine("Boolean Value : " + reader.ReadBoolean());
            }
        }
    }

Output

Double Value : 12.5

String Value : this is string data

Boolean Value : true