Curriculum
In C#, the BinaryWriter class is used to write binary data to a stream. It provides methods for writing various types of data, including integers, floating-point values, and strings, to a stream in binary format.
Here is an example of using BinaryWriter to write binary data to a file:
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.bin";
using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Create)))
{
writer.Write(42);
writer.Write(3.14);
writer.Write("Hello, world!");
}
}
}
In this example, we create a BinaryWriter object by specifying a file path. We then use the Write method to write an integer, a floating-point value, and a string to the file in binary format.
Here is an example of using BinaryWriter to write binary data to a MemoryStream:
using System;
using System.IO;
class Program
{
static void Main()
{
using (MemoryStream stream = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(42);
writer.Write(3.14);
writer.Write("Hello, world!");
}
byte[] data = stream.ToArray();
Console.WriteLine(BitConverter.ToString(data));
}
}
}
In this example, we create a MemoryStream object and use it to create a BinaryWriter object. We then use the Write method to write an integer, a floating-point value, and a string to the stream in binary format. Finally, we convert the contents of the MemoryStream to a byte array and print it to the console.
Overall, BinaryWriter is a useful class for writing binary data to streams in C#. It provides a high-level, convenient way to write data, but it does not provide the low-level control and efficiency of FileStream. It also requires careful attention to detail and proper error handling to ensure that streams are written correctly.