BinaryWriter Class

Namespace: System.IO
Assembly: System.Runtime.dll

Summary

Writes primitive types in binary format to a stream and supports writing strings in a specified encoding. This class cannot be inherited.

Remarks

Use the BinaryWriter class to write primitive data types (Booleans, bytes, characters, doubles, integers, etc.) to a stream. The BinaryWriter class also supports writing strings in a specific encoding. This class is useful for creating binary files that can be read by other applications or by the BinaryReader class. It is important to note that BinaryWriter writes data in a specific format, and this format is not necessarily human-readable. If you need to write data in a human-readable format, consider using a text-based format like CSV or JSON.

Properties

Name Description
BaseStream Gets the underlying stream.

Constructors

BinaryWriter(Stream output) - Initializes a new instance of the BinaryWriter class.

Initializes a new instance of the BinaryWriter class based on the supplied stream and a UTF-8 encoding. If the stream is already considered closed, this method throws an ArgumentException.

Parameter Description
output The stream to write to.
BinaryWriter(Stream output, Encoding encoding) - Initializes a new instance of the BinaryWriter class.

Initializes a new instance of the BinaryWriter class based on the supplied stream and character encoding. If the stream is already considered closed, this method throws an ArgumentException.

Parameter Description
output The stream to write to.
encoding The character encoding to use.
BinaryWriter(Stream output, Encoding encoding, bool leaveOpen) - Initializes a new instance of the BinaryWriter class.

Initializes a new instance of the BinaryWriter class based on the supplied stream and character encoding, and optionally leaves the stream open. If the stream is already considered closed, this method throws an ArgumentException.

Parameter Description
output The stream to write to.
encoding The character encoding to use.
leaveOpen true to leave the stream open after the BinaryWriter object is disposed; otherwise, false.

Methods

void Write(bool value) - Writes a Boolean value to the current stream and advances the stream position.

Writes a Boolean value to the current stream and advances the stream position by one byte.

Parameter Description
value The Boolean value to write.
void Write(byte[] buffer) - Writes a byte array to the current stream and advances the stream position.

Writes a region of a byte array to the current stream and advances the stream position by the number of bytes written.

Parameter Description
buffer The byte array to write.
void Write(char ch) - Writes a Unicode character to the current stream and advances the stream position.

Writes a Unicode character to the current stream and advances the stream position. This method writes the character as a variable-length UTF-8 encoded byte sequence. For a fixed-length representation, use Write(Char).

Parameter Description
ch The character to write.
void Write(decimal value) - Writes a decimal value to the current stream and advances the stream position.

Writes a decimal value to the current stream and advances the stream position.

Parameter Description
value The decimal value to write.
void Write(double value) - Writes a double-precision floating-point value to the current stream and advances the stream position.

Writes a double-precision floating-point value to the current stream and advances the stream position.

Parameter Description
value The double-precision floating-point value to write.
void Write(short value) - Writes a 16-bit integer to the current stream and advances the stream position.

Writes a 16-bit integer to the current stream and advances the stream position by two bytes.

Parameter Description
value The 16-bit integer to write.
void Write(int value) - Writes a 32-bit integer to the current stream and advances the stream position.

Writes a 32-bit signed integer to the current stream and advances the stream position by four bytes.

Parameter Description
value The 32-bit integer to write.
void Write(long value) - Writes a 64-bit integer to the current stream and advances the stream position.

Writes a 64-bit signed integer to the current stream and advances the stream position by eight bytes.

Parameter Description
value The 64-bit integer to write.
void Write(string s) - Writes a string to the current stream and advances the stream position.

Writes a string to the current stream and advances the stream position. This method writes the string using UTF-8 encoding.

Parameter Description
s The string to write.
void Flush() - Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.

Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.

void Close() - Closes the current BinaryWriter and the underlying stream.

Closes the BinaryWriter and the underlying stream.

BaseStream Property

Gets the underlying stream.

public virtual Stream BaseStream { get; }

The stream to which the BinaryWriter is writing.

Example

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

public class Example
{
    public static void Main()
    {
        string path = @"c:\temp\MyBinaryFile.bin";

        // Create some data to write
        int employeeId = 101;
        string name = "Alice";
        double salary = 75000.50;
        bool isFullTime = true;

        try
        {
            // Use a FileStream and BinaryWriter to write data
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            using (BinaryWriter writer = new BinaryWriter(fs, Encoding.UTF8, false))
            {
                Console.WriteLine($"Writing data to {path}...");

                writer.Write(employeeId);       // Write integer
                writer.Write(name);             // Write string
                writer.Write(salary);           // Write double
                writer.Write(isFullTime);       // Write boolean

                Console.WriteLine("Data written successfully.");
            }

            // Use a FileStream and BinaryReader to read data back
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            using (BinaryReader reader = new BinaryReader(fs, Encoding.UTF8, false))
            {
                Console.WriteLine($"\nReading data from {path}...");

                int readEmployeeId = reader.ReadInt32();
                string readName = reader.ReadString();
                double readSalary = reader.ReadDouble();
                bool readIsFullTime = reader.ReadBoolean();

                Console.WriteLine($"Employee ID: {readEmployeeId}");
                Console.WriteLine($"Name: {readName}");
                Console.WriteLine($"Salary: {readSalary}");
                Console.WriteLine($"Is Full Time: {readIsFullTime}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}