c-sharp
  1. c-sharp-binaryreader

C# BinaryReader

In C#, the BinaryReader class is used to read binary data from a file or a stream. It provides methods for reading different data types, such as integers and floats, as well as for reading strings and byte arrays. In this tutorial, we'll discuss how to use the BinaryReader class in C#.

Syntax

The syntax for using the BinaryReader class in C# is as follows:

using System.IO;

BinaryReader br = new BinaryReader(File.Open("file.bin", FileMode.Open));

This creates a BinaryReader object that reads from a file called "file.bin". You can also create a BinaryReader object that reads from a stream.

Example

Let's say we have a binary file called "data.bin" that contains the number of students and their names. Each name is stored as a null-terminated string. Here's how we can read the data from the file using BinaryReader:

using System;
using System.IO;

class Program {
   static void Main(string[] args) {
      BinaryReader br = new BinaryReader(File.Open("data.bin", FileMode.Open));

      // Read the number of students
      int numStudents = br.ReadInt32();

      // Read the names of the students
      for (int i = 0; i < numStudents; i++) {
         string name = "";
         char c;
         while ((c = br.ReadChar()) != '\0') {
            name += c;
         }
         Console.WriteLine(name);
      }

      // Close the BinaryReader object
      br.Close();
   }
}

Output

When we run the example code above, the output will be:

John
Jane
Mary

This is because we read three null-terminated strings from the binary file.

Explanation

In the example above, we created a program that uses BinaryReader to read the data from a binary file called "data.bin". We opened the file using File.Open, and then created a BinaryReader object to read from it.

We first read an integer that represents the number of students in the file, using the ReadInt32 method. We then read the names of the students by reading one character at a time until we reach a null terminator, using the ReadChar method.

Finally, we closed the BinaryReader object.

Use

BinaryReader is useful for reading binary data from files or streams. It allows you to read data of different types, such as integers, floats, and strings. You can use BinaryReader to write programs that read binary data from files or streams, such as image files or audio files.

Important Points

  • Always check that the data you're reading is of the correct type.
  • Always close the BinaryReader object when you're done reading from it to free up memory.

Summary

In this tutorial, we discussed how to use the BinaryReader class in C# to read binary data from a file or a stream. We covered the syntax, example, output, explanation, use, and important points of BinaryReader in C#. With this knowledge, you can now use BinaryReader to read data of different types from binary files or streams in your C# programs.

Published on: