C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In this tutorial, we'll demonstrate how to use the BinaryReader
class in C# to read binary files. The BinaryReader
class is part of the System.IO
namespace and provides methods for reading binary data from a stream.
Create a new C# Console Application project in Visual Studio and add the following namespaces:
using System.IO; using System.Text;
For this tutorial, we need a binary file to read. You can create a binary file using the BinaryWriter
class. The following code writes a string, an integer, and a double to a binary file named data.bin
:
using (FileStream fs = new FileStream("data.bin", FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(fs, Encoding.UTF8)) { bw.Write("Hello, BinaryReader!"); bw.Write(42); bw.Write(3.14); } }
To read the binary file created in the previous step, use the BinaryReader
class. The following code reads the string, integer, and double from the data.bin
file:
using (FileStream fs = new FileStream("data.bin", FileMode.Open)) { using (BinaryReader br = new BinaryReader(fs, Encoding.UTF8)) { string text = br.ReadString(); int number = br.ReadInt32(); double value = br.ReadDouble(); Console.WriteLine($"Text: {text}"); Console.WriteLine($"Number: {number}"); Console.WriteLine($"Value: {value}"); } }
When you run the Console Application, you should see the following output:
Text: Hello, BinaryReader! Number: 42 Value: 3.14
In this tutorial, we've shown you how to use the BinaryReader
class in C# to read binary files. The BinaryReader
class provides methods for reading binary data from a stream, making it easy to read different data types from binary files.
C# BinaryReader example:
BinaryReader
class in C#, which provides methods for reading binary data from streams.using (FileStream fileStream = new FileStream("binaryfile.bin", FileMode.Open)) using (BinaryReader binaryReader = new BinaryReader(fileStream)) { // Read binary data using BinaryReader methods int intValue = binaryReader.ReadInt32(); double doubleValue = binaryReader.ReadDouble(); // ... continue reading as needed }
Seeking and navigating in binary files with BinaryReader C#:
Seek
method of BinaryReader
to navigate to a specific position in a binary file.using (FileStream fileStream = new FileStream("binaryfile.bin", FileMode.Open)) using (BinaryReader binaryReader = new BinaryReader(fileStream)) { // Seek to a specific position in the file binaryReader.BaseStream.Seek(8, SeekOrigin.Begin); // Read data from the new position double newValue = binaryReader.ReadDouble(); }