📜  C#BinaryWriter(1)

📅  最后修改于: 2023-12-03 15:30:16.625000             🧑  作者: Mango

C# BinaryWriter

Introduction

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.

Syntax

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:

  • output: A stream to write to.
  • encoding: An Encoding object specifying the character encoding to use. If not specified, the UTF-8 encoding is used.
  • leaveOpen: A boolean value indicating whether to leave the underlying stream open after the BinaryWriter is disposed. If not specified, false is used.
  • bufferSize: An integer value specifying the buffer size to use when writing. If not specified, the default buffer size is used.
Example

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.

Conclusion

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.