BinaryWriter Class
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
Methods
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}");
}
}
}