Home C# BinaryWriter in C# tutorials

BinaryWriter in C# tutorials

BinaryWriter in C# is a class that enables writing primitive types (like integers, floats, strings) to a binary stream in a specific encoding.

It’s part of the System.IO namespace and is typically used to write data in a binary format rather than human-readable text, making it useful for file storage and data transmission.

In this tutorial, we’ll cover:

1. Basics of BinaryWriter

BinaryWriter writes data to a stream in binary format, storing values directly in bytes. This differs from StreamWriter, which writes text data. You can use BinaryWriter with different streams, such as FileStream for writing to files.

Basic Syntax for Using BinaryWriter:

using System.IO;

using (BinaryWriter writer = new BinaryWriter(new FileStream("file.bin", FileMode.Create)))
{
    // Writing code goes here
}

The using statement ensures that the BinaryWriter object is properly closed after use, releasing any resources it holds.

2. Writing Primitive Data Types with BinaryWriter

BinaryWriter provides methods to write various primitive data types, such as Write(int), Write(double), Write(bool), etc. These methods store the data in a binary format.

Example: Writing Primitive Data Types

using System;
using System.IO;

public class BinaryWriterExample
{
    public static void Main()
    {
        using (BinaryWriter writer = new BinaryWriter(new FileStream("data.bin", FileMode.Create)))
        {
            writer.Write(42);         // Write an integer
            writer.Write(3.14f);      // Write a float
            writer.Write(true);       // Write a boolean
            writer.Write(123.456);    // Write a double
            Console.WriteLine("Primitive data written to binary file.");
        }
    }
}

Explanation:

  • Write(int), Write(float), Write(bool), and Write(double) write data as binary bytes.
  • This approach is more compact and efficient than storing data in text format.

3. Writing and Reading Strings in Binary Format

You can write strings in binary format using BinaryWriter. The BinaryReader class is used to read the data back, which we'll cover in the reading example.

Example: Writing and Reading Strings in Binary Format

using System;
using System.IO;

public class BinaryWriterReaderExample
{
    public static void Main()
    {
        // Writing a string to a binary file
        using (BinaryWriter writer = new BinaryWriter(new FileStream("stringData.bin", FileMode.Create)))
        {
            writer.Write("Hello, BinaryWriter!"); // Write a string
            writer.Write("Another line of text.");
            Console.WriteLine("Strings written to binary file.");
        }

        // Reading the strings back from the binary file
        using (BinaryReader reader = new BinaryReader(new FileStream("stringData.bin", FileMode.Open)))
        {
            string message1 = reader.ReadString();
            string message2 = reader.ReadString();
            Console.WriteLine("Read from binary file:");
            Console.WriteLine(message1);
            Console.WriteLine(message2);
        }
    }
}

Explanation:

  • Write(string) writes strings as binary data to the file stringData.bin.
  • ReadString() from BinaryReader reads the string back in the same order it was written, as binary data maintains no newline separator.

Output:

Strings written to binary file.
Read from binary file:
Hello, BinaryWriter!
Another line of text.

4. Working with Binary Data Using FileStream

BinaryWriter can write binary data to a file, while FileStream allows us to manage the file opening, closing, and access modes. Here’s an example using FileStream to write a list of numbers in binary.

Example: Writing a List of Integers to a Binary File

using System;
using System.IO;

public class BinaryFileStreamExample
{
    public static void Main()
    {
        int[] numbers = { 10, 20, 30, 40, 50 };

        using (FileStream fileStream = new FileStream("numbers.bin", FileMode.Create))
        using (BinaryWriter writer = new BinaryWriter(fileStream))
        {
            foreach (int number in numbers)
            {
                writer.Write(number); // Write each integer in binary format
            }
            Console.WriteLine("Array of integers written to binary file.");
        }

        // Reading the integers back from the file
        using (BinaryReader reader = new BinaryReader(new FileStream("numbers.bin", FileMode.Open)))
        {
            Console.WriteLine("Reading integers from binary file:");
            for (int i = 0; i < numbers.Length; i++)
            {
                Console.WriteLine(reader.ReadInt32());
            }
        }
    }
}

Explanation:

  • Each integer in numbers is written in binary format to numbers.bin.
  • BinaryReader reads the integers back in the same order as they were written.

Output:

Array of integers written to binary file.
Reading integers from binary file:
10
20
30
40
50

5. Practical Example: Saving and Loading Structured Data with BinaryWriter and BinaryReader

In this example, we’ll save and load a list of structured data (e.g., student records) to and from a binary file.

Example: Saving and Loading Student Records

using System;
using System.IO;

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public double GPA { get; set; }
}

public class StudentDataBinaryExample
{
    public static void SaveStudentData(Student[] students, string filePath)
    {
        using (BinaryWriter writer = new BinaryWriter(new FileStream(filePath, FileMode.Create)))
        {
            writer.Write(students.Length); // Write the number of students
            foreach (var student in students)
            {
                writer.Write(student.ID);
                writer.Write(student.Name);
                writer.Write(student.GPA);
            }
        }
        Console.WriteLine("Student data saved to binary file.");
    }

    public static void LoadStudentData(string filePath)
    {
        using (BinaryReader reader = new BinaryReader(new FileStream(filePath, FileMode.Open)))
        {
            int studentCount = reader.ReadInt32(); // Read the number of students
            Console.WriteLine($"Number of students: {studentCount}");

            for (int i = 0; i < studentCount; i++)
            {
                int id = reader.ReadInt32();
                string name = reader.ReadString();
                double gpa = reader.ReadDouble();
                Console.WriteLine($"ID: {id}, Name: {name}, GPA: {gpa}");
            }
        }
    }

    public static void Main()
    {
        Student[] students = new Student[]
        {
            new Student { ID = 1, Name = "Alice", GPA = 3.5 },
            new Student { ID = 2, Name = "Bob", GPA = 3.8 },
            new Student { ID = 3, Name = "Charlie", GPA = 3.2 }
        };

        string filePath = "students.bin";
        
        SaveStudentData(students, filePath);
        LoadStudentData(filePath);
    }
}

Explanation:

  • SaveStudentData() writes the list of students to students.bin. It writes the count of students first, then each student’s ID, Name, and GPA.
  • LoadStudentData() reads the binary file, retrieves each student’s details, and displays them.

Output:

Student data saved to binary file.
Number of students: 3
ID: 1, Name: Alice, GPA: 3.5
ID: 2, Name: Bob, GPA: 3.8
ID: 3, Name: Charlie, GPA: 3.2

Summary

BinaryWriter in C# is an efficient way to write primitive data types to a binary file, providing a compact and optimized format for data storage and transfer. Here’s a recap of key concepts:

  • Basic Setup: Use BinaryWriter with FileStream for file I/O, ensuring resources are managed with using.
  • Writing Primitive Types: Use methods like Write(int), Write(double), Write(string) to store data in binary format.
  • String Data: Write(string) allows writing text in binary, which can be read back with BinaryReader.
  • Using with FileStream: BinaryWriter with FileStream enables efficient, low-level access to binary data storage.
  • Structured Data: Save and load complex data structures (like student records) in binary format for efficiency.

Using BinaryWriter in C# is ideal for applications needing compact, high-performance data storage solutions, particularly for structured and numeric data.

You may also like