C# BinaryWriter is a class in the .NET framework that allows you to write primitive data types as binary values to a stream. It is typically used when you need to write binary data to a file or any other output stream.
To use BinaryWriter, you first need to create an instance of the class and provide it with a stream to write to. Here’s an example of how to use BinaryWriter to write data to a file:
using (var fileStream = new FileStream("data.bin", FileMode.Create)) { using (var binaryWriter = new BinaryWriter(fileStream)) { // Write some data int intValue = 42; binaryWriter.Write(intValue); float floatValue = 3.14f; binaryWriter.Write(floatValue); string stringValue = "Hello, world!"; binaryWriter.Write(stringValue); } }
In the example above, we create a FileStream
with FileMode.Create
to create a new file called “data.bin”. Then we create a BinaryWriter
instance and pass the file stream to it. We can then use the Write
methods of the BinaryWriter
to write different types of data to the file.
In this case, we write an integer, a float, and a string to the file. The Write
method automatically converts the data to its binary representation and writes it to the stream.
After we finish writing the data, we close the BinaryWriter
and the FileStream
by using the using
statement. This ensures that the resources are properly disposed of, even if an exception occurs.
It’s important to note that when reading the data back, you need to use the corresponding BinaryReader
class to read the data in the same order and format that it was written.