BinaryWirter
BinaryWriter is a class in the System.IO namespace that provides a way to write binary data to a stream. It can write primitive types, such as integers and floating-point numbers, as well as strings and arrays of bytes.
BinaryWriter is typically used in conjunction with BinaryReader, which provides a way to read binary data from a stream.
Here are some of the most commonly used methods of BinaryWriter:
Write: Writes a single byte to the output stream.
WriteBoolean: Writes a Boolean value to the output stream.
WriteInt32: Writes a 32-bit integer to the output stream.
WriteString: Writes a string to the output stream.
Here's an example that demonstrates how to use BinaryWriter to write binary data to a file:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = @"C:\example.bin";
using (BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create)))
{
writer.Write(42);
writer.Write("Hello, world!");
writer.Write(new byte[] { 0x01, 0x02, 0x03 });
}
}
}
In this example, we create a new BinaryWriter object that writes to a new file at the specified path. We then use the Write method to write an integer, a string, and an array of bytes to the file. The using statement ensures that the writer is properly disposed of when we're finished with it.
Comments
Post a Comment