Home  >  Article  >  Backend Development  >  C# BinaryReader

C# BinaryReader

WBOY
WBOYOriginal
2024-09-03 15:22:40490browse

In C#, BinaryReader is a class used to handle binary data. It is found under System.IO namespace. BinaryReader is used to read primitive data types as binary values in a particular encoding stream. BinaryReader works with Stream object i.e. in order to create an object of BinaryReader, we need to pass Stream object in its constructor. BinaryReader class has three overloaded constructors to work with binary data. By default, BinaryReader uses UTF-8 encoding to read data until we specify other character encodings while creating its object.

Syntax with explanation

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

BinaryReader binary_reader = new BinaryReader(inputStream);

The above statement initializes a new instance of BinaryReader based on the specified stream (inputStream) by using UTF-8 encoding.

BinaryReader binary_reader = new BinaryReader(inputStream, encoding);

This statement initializes a new instance of BinaryReader based on the specified stream (inputStream) and encoding specified by encoding.

BinaryReader binary_reader = new BinaryReader(inputStream, encoding, true);

This statement works the same as the above two statements with an extra parameter of type Boolean which is used to specify if the user wants to leave the stream open after the object of BinaryReader is disposed of. This parameter needs to be ‘true’ to leave the stream open otherwise it needs to be ‘false’.

Apart from these three ways, we can also create BinaryReader using the following statements:

using(BinaryReader binary_reader = new BinaryReader(File.Open(file_path, FileMode.Open)))
{
//user code
}

In the above statement, File.Open() method returns an object of FileStream and thus it helps in creating the object of BinaryReader.

The benefit of creating an object inside the ‘using’ block is that it releases the memory held by the object when the work of the object is completed and it is no longer required.

How BinaryReader works in C#?

BinaryReader is used to read binary information i.e. it is used to read data stored in binary files. Binary file stores data in a way which can be easily understood by a machine but for human it is very difficult to understand such data. To help understand such data BinaryReader is used. In order to work with BinaryReader, we first need to import System.IO namespace in our code. After this, we need to create an instance of BinaryReader with the help of a ‘new’ operator and bypassing the object of Stream inside the constructor of BinaryReader.

While creating an instance of BinaryReader we provide stream to read from then we can optionally specify the character encoding to be used if we do not specify encoding, by default UTF-8 encoding is used. Along with this, we can optionally specify if we want the stream to be opened after the object of BinaryReader is disposed of as shown in the below statement.

BinaryReader binary_reader = new BinaryReader(inputStream, encoding, true);

Then with the help of different Read() methods of BinaryReader which are provided for different data types, we can read data from the file.

BinaryReader has many Read() methods that support different data types and they are used to read primitive data types from a stream. Such as the ReadString() method of BinaryReader is used to read the next byte as string value and also it advances the current position in the stream by one byte.

Read() methods of BinaryReader for different types of data in the following table:

Method Description
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.

Example of C# Binaryreader

Example of creating a file using BinaryWriter and reading it using BInaryReader.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp4
{
public class Program
{
string filePath = "E:\\Content\\binaryFile.dat";
public void WriteFile()
{
try
{
//checking if the file already exists
if (File.Exists(filePath))
{
File.Delete(filePath);
}
FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.ReadWrite);
//creating binary file using BinaryWriter
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write("This is string");
writer.Write(100.53);
writer.Write(true);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void ReadFile()
{
try
{
//creating an object of Stream
FileStream stream = new FileStream(filePath, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
//creating BinaryReader using Stream object
using (BinaryReader reader = new BinaryReader(stream))
{
//reading data using Read() methods of different data types
Console.WriteLine("String Value : " + reader.ReadString());
Console.WriteLine("Double Value : " + reader.ReadDouble());
Console.WriteLine("Boolean Value : " + reader.ReadBoolean());
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public class BinaryReaderDemo
{
static void Main(string[] args)
{
Program obj = new Program();
obj.WriteFile();
obj.ReadFile();
Console.ReadKey();
}
}
}

Output:

C# BinaryReader

Conclusion

BinaryReader is used to read primitive data types as binary values in a specific encoding stream. If not defined explicitly, by default BinaryReader uses UTF-8 encoding to read data. Stream object needs to be passed inside the constructor of BinaryReader in order to create its instance.

The above is the detailed content of C# BinaryReader. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:BinaryWriter in C#Next article:BinaryWriter in C#