Curriculum
BinaryReader is a class in C# that allows you to read binary data from a stream, such as a file or a network socket. It is useful when you need to read structured data that is not in text format, such as integers, floating-point numbers, and strings.
Here is an example of using BinaryReader to read data from a binary file:
using System; using System.IO; class Program { static void Main(string[] args) { // Open the binary file for reading using (BinaryReader reader = new BinaryReader(File.Open("data.bin", FileMode.Open))) { // Read an integer from the file int num1 = reader.ReadInt32(); Console.WriteLine("Num1: {0}", num1); // Read a float from the file float num2 = reader.ReadSingle(); Console.WriteLine("Num2: {0}", num2); // Read a string from the file string str = reader.ReadString(); Console.WriteLine("String: {0}", str); } } }
In this example, we first create a BinaryReader
object by passing a file stream to its constructor. We then use the ReadInt32
, ReadSingle
, and ReadString
methods to read an integer, a float, and a string from the file, respectively.
It’s important to note that the order and type of data you read from the file must match the order and type of data that was written to the file using a BinaryWriter
. Additionally, you should always dispose of the BinaryReader
object once you’re finished using it, which is achieved by wrapping it in a using
statement.