BinaryReader
BinaryReader is a class in the System.IO namespace that provides a way to read binary data from a stream. It can read primitive types, such as integers and floating-point numbers, as well as strings and arrays of bytes.
BinaryReader is typically used in conjunction with BinaryWriter, which provides a way to write binary data to a stream.
Here are some of the most commonly used methods of BinaryReader:
ReadByte: Reads a single byte from the input stream.
ReadBoolean: Reads a Boolean value from the input stream.
ReadInt32: Reads a 32-bit integer from the input stream.
ReadString: Reads a string from the input stream.
Here's an example that demonstrates how to use BinaryReader to read binary data from a file:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = @"C:\example.bin";
using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open)))
{
int number = reader.ReadInt32();
string text = reader.ReadString();
byte[] bytes = reader.ReadBytes(3);
Console.WriteLine(number);
Console.WriteLine(text);
Console.WriteLine(BitConverter.ToString(bytes));
}
}
}
In this example, we create a new BinaryReader object that reads from an existing file at the specified path. We then use the ReadInt32, ReadString, and ReadBytes methods to read an integer, a string, and an array of bytes from the file. We then output the results to the console. The using statement ensures that the reader is properly disposed of when we're finished with it.
Comments
Post a Comment