BinaryWriter Class

Writes primitive types in binary format to a stream and supports writing strings in a specific encoding.

Syntax

public class BinaryWriter : IDisposable

Introduction

The BinaryWriter class provides methods for writing various data types (like integers, floating-point numbers, booleans, and strings) in a binary format to an underlying stream. This is useful for creating custom file formats or for inter-process communication where precise control over data representation is required. It ensures that data is written in a platform-independent manner.

Constructors

Methods

Example

Writing data to a binary file

using System;
using System.IO;
using System.Text;

public class Example
{
    public static void Main()
    {
        string filePath = "data.bin";
        using (FileStream fs = new FileStream(filePath, FileMode.Create))
        using (BinaryWriter writer = new BinaryWriter(fs, Encoding.UTF8))
        {
            writer.Write(123);                     // int
            writer.Write(45.67);                   // double
            writer.Write(true);                    // bool
            writer.Write("Hello, BinaryWriter!");  // string
            writer.Write(new byte[] { 0x01, 0x02, 0x03 }); // byte array
        }
        Console.WriteLine($"Data written to {filePath}");
    }
}

Requirements

Namespace: System.IO

Assembly: mscorlib.dll

Remarks

When you create an instance of BinaryWriter, you can specify an encoding. The default is UTF-8. If you want to write data that can be read by other applications or systems, it's crucial to use a consistent encoding.

The BinaryWriter class does not support seeking. If you need to seek within the stream, you should use a stream that supports seeking, such as FileStream, and call its Seek method before writing.

Remember to dispose of the BinaryWriter instance when you are finished with it, either by calling Close() or by using a using statement, to ensure that all buffered data is flushed and resources are released.