📅  最后修改于: 2023-12-03 15:30:16.625000             🧑  作者: Mango
The BinaryWriter class in C# is a utility class that allows you to write primitive data types to a stream in a binary format. This is usually used when you need to save data to a file or transfer it over a network.
BinaryWriter class is an important part of the System.IO namespace and provides a simple interface for writing to streams. While reading data, you use the BinaryReader class.
The BinaryWriter class provides four constructors:
BinaryWriter(Stream output);
BinaryWriter(Stream output, Encoding encoding);
BinaryWriter(Stream output, Encoding encoding, bool leaveOpen);
BinaryWriter(Stream output, Encoding encoding, int bufferSize, bool leaveOpen);
The parameters are as follows:
You can write data to a file using the BinaryWriter class as follows:
using (BinaryWriter writer = new BinaryWriter(File.Open("data.bin", FileMode.Create)))
{
writer.Write(42);
writer.Write("Hello, World!");
writer.Write(3.14159);
}
This code will write an integer, a string, and a double to a file named data.bin.
You can also write to a MemoryStream:
using (MemoryStream stream = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(42);
writer.Write("Hello, World!");
writer.Write(3.14159);
}
byte[] buffer = stream.ToArray();
}
In this code, we write the same data to a MemoryStream, then retrieve the bytes using the ToArray()
method.
The BinaryWriter class is a useful tool for writing data in a binary format in C#. It provides a simple interface for writing to streams.