C# Binaryreader

In C#, the BinaryReader class is employed to extract binary information from a stream within the System.IO namespace. It provides functionality to interpret strings in a particular encoding. This class, residing in the System.IO namespace, facilitates the reading of basic data types. By default, the BinaryReader utilizes UTF-8 encoding for data interpretation unless an alternative character encoding is specified upon object instantiation.

The <style> element is a representation of a code snippet. It includes a diagram with a background styled using a linear gradient from #374151 to #1f2937, with rounded corners, padding of 40px, and a margin of 20px top and bottom. The content is centered within the diagram. A placeholder icon with a size of 3rem is displayed above the placeholder text, which is styled in a color of #9ca3af and a font size of 1rem. </style>

Syntax:

It has the following syntax.

Example

BinaryReader reader = new BinaryReader(Stream input);

Or with encoding:

Example

BinaryReader reader = new BinaryReader(Stream input, Encoding encoding);

In this format,

  • Input Stream: This signifies the stream, like a FileStream, that contains the binary data to read.
  • Character encoding: This indicates the required character encoding for the operation.
  • Simple C# BinaryReader Class Example

Let's consider a scenario to demonstrate the BinaryReader class in C#.

Example

Example

using System;

using System.IO;

class C# Tutorial

{

    static void Main()

    {

        string filePath = "example.bin";

        using(BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Create)))

        {

            writer.Write(555);           // Write an integer

            writer.Write(45.67);         // Write a double

            writer.Write("Hello, Welcome to C# Programming tech");    // Write a string

        }

        // Reading the data of BinaryReader

        using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))

        {

            int intValue = reader.ReadInt32();

            double doubleValue = reader.ReadDouble();

            string stringValue = reader.ReadString();

            Console.WriteLine("The integer value is " + intValue);

            Console.WriteLine("The double value is " + doubleValue);

            Console.WriteLine("The string value is " + stringValue);

        }

    }

}

Output:

Output

The integer value is 555

The double value is 45.67

The string value is Hello, Welcome to C# Programming tech

Explanation:

In this instance, we showcase the application of the BinaryReader classes in C#. Initially, we generate a binary file named example.bin, where we store three different kinds of information: integer, double, and string. Following this, we employ the BinaryReader class to retrieve the information from the file. Finally, we utilize the Console.WriteLine function to display the retrieved data.

Methods of the BinaryReader Class in C#

Within the C# programming language, the BinaryReader Class encompasses a variety of methods, including the following:

Method Description
Read() The Read() method is commonly utilized to read the characters from the current stream.
ReadByte() The ReadByte() method is utilized to read the next byte from the latest position in the binary stream.
ReadBoolean() The ReadBoolean() method is commonly utilized to read the Boolean value from the current position in the binary stream.
ReadDouble() The ReadDouble() method is commonly utilized to read the floating point value from the current position in the binary stream.
ReadString() The ReadStriing() method is utilized to read the string value from the current stream.
ReadChar() The ReadChar() method is commonly utilized to extract data from a file.
ReadChars(int count) It is used to read the specified number of characters from a stream or source.
ReadInt32() It is commonly utilized to read the 4-byte signed integer from the existing stream and enhance the current position of the stream by four bytes.
ReadInt16() It is commonly utilized to read the 2-byte signed integer from the current position of the stream.
ReadDecimal() It is utilized to read the decimal value from the current position of the stream.
Close() The Close() method is utilized to close the BinaryReader and the underlying stream.

C# Example to Read and Write Multiple Data Types Using BinaryReader and BinaryWriter

Let's consider an example to explain the functions of the BinaryReader class in C#.

Example

Example

using System;

using System.IO;

class C# Tutorial

{

    static void Main()

    {

        string filePath = "ex.bin";

        using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Create)))

        {

            writer.Write(125);

            writer.Write(35.75);

            writer.Write(true);                    

            writer.Write('M');                      

            writer.Write("Hello, Welcome to C# Programming");   

        }

        using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))

        {

            int n = reader.ReadInt32();         

            double p = reader.ReadDouble();       

            bool s = reader.ReadBoolean();

            char g = reader.ReadChar(); 

            string m = reader.ReadString();     

            Console.WriteLine("The integer value is " + n);

            Console.WriteLine("The double value is " + p);

            Console.WriteLine("The boolean value is " + s);

            Console.WriteLine("TThe character value is " + g);

            Console.WriteLine("The string value is " + m);

        }

    }

}

Output:

Output

The integer value is 125

The double value is 35.75

The boolean value is True

The character value is M

The string value is Hello, Welcome to C# Programming

Explanation:

In this illustration, we generate a file called ex.bin employing BinaryWriter. BinaryWriter translates each data point into its binary format. Subsequently, BinaryReader scans the identical file and fetches the information sequentially. Following this, we employ the Console.WriteLine function to display the fetched values.

C# BinaryReader Function Example with ReadString Method

Let's consider a scenario to demonstrate the application of the ReadString function within the BinaryReader class in C#.

Example

Example

using System;

using System.IO;

class C# Tutorial

{

    static void Main()

    {

        string path = "exp.bin";

        // Writing data to a binary file

        using (BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create)))

        {

            writer.Write("Welcome to C# Programming");

        }

        // Reading data from the binary file

        using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open)))

        {

            string mes = reader.ReadString();

            Console.WriteLine("Message: " + mes);

        }

    }

}

Output:

Output

Message: Welcome to C# Programming

Explanation:

In this illustration, a class called C# Tutorial is instantiated. Within the main function, a binary file named exp.bin is generated via the Binary class. Subsequently, the BinaryReader class is employed to retrieve the identical string from the file, followed by the utilization of the Console.WriteLine method to exhibit the outcome.

Features of the BinaryReader Method in C#

Several features of the BinaryReader Method in C# sare as follows:

  • It is commonly used to read primitive data types as binary values rather than text.
  • It is very helpful to read the data in the same order in which it was written in BinaryWriter in C#.
  • It uses IDisposable in C# programs, which enables the resources to be released automatically.
  • It provides read characters with custom text encodings.
  • It helps in error handling during the binary tasks in C#.
  • Conclusion

In summary, a BinaryReader is a class designed to extract binary data from a stream. It can also handle reading strings encoded in a particular format. This class offers various functions for extracting basic data types such as integers, doubles, booleans, strings, and more. This functionality aids in securely and efficiently reading code from diverse origins.

C# BinaryReader FAQs

1) What is the BinaryReader class in C#?

In C#, the BinaryReader class is employed for extracting binary data from a stream. It is located within the System.IO namespace and enables reading strings using a designated encoding. This class is part of the System.IO namespace.

In C#, the BinaryReader class is located within the System.IO namespace.

The BinaryReader class is located within the System.IO namespace, which contains a variety of classes designed for conducting input and output tasks. These include activities like retrieving and storing data from files and streams.

3) How do we create a BinaryReader object?

In C#, a BinaryReader instance can be instantiated by providing a stream as an argument to its constructor. The syntax for creating a BinaryReader object is as follows:

Example

BinaryReader reader = new BinaryReader(Stream input);

The ReadInt32 method in the BinaryReader class in C# is utilized for reading a 32-bit signed integer from the current stream and advancing the position of the stream by four bytes.

In C#, the ReadInt32 function is employed to extract the 4-byte signed integer from the stream and move the stream's current position forward by four bytes.

The ReadString method in the BinaryReader class in C# is used to read a string from the current stream.

In C# programming, the ReadString function is employed to extract the string data from the existing stream. Initially, this function retrieves the string's length as recorded in the stream, and subsequently retrieves the corresponding characters to reconstruct the initial string.

Input Required

This code uses input(). Please provide values below: