📜  C#BinaryReader(1)

📅  最后修改于: 2023-12-03 14:40:28.408000             🧑  作者: Mango

C# BinaryReader

The BinaryReader class is a part of the System.IO namespace in C#. It provides methods to read primitive data types from a stream in a binary format. It is commonly used to read data from a binary file, but can also be used to read data from a network socket or other data source.

Creating a BinaryReader

To create a BinaryReader, you need to pass a Stream object to its constructor. Here's an example:

Stream stream = File.OpenRead("data.bin");
BinaryReader reader = new BinaryReader(stream);

In this example, we create a Stream object from a binary file using File.OpenRead, and pass it to the BinaryReader constructor.

Reading Data Types

The BinaryReader class provides methods to read various data types from a stream. Here are some examples:

// Read a byte
byte b = reader.ReadByte();

// Read a short
short s = reader.ReadInt16();

// Read an int
int i = reader.ReadInt32();

// Read a long
long l = reader.ReadInt64();

// Read a float
float f = reader.ReadSingle();

// Read a double
double d = reader.ReadDouble();

// Read a decimal
decimal dec = reader.ReadDecimal();

// Read a boolean
bool b = reader.ReadBoolean();

// Read a char
char c = reader.ReadChar();
Reading Strings

To read a string from a binary file, you can use the ReadString method. This method reads a length-prefixed string from the stream, where the length is a 7-bit encoded integer.

Here's an example:

string str = reader.ReadString();
Closing the BinaryReader

After you've finished reading data from the stream, you should close the BinaryReader to release any resources it's using. You can do this by calling its Close method:

reader.Close();
Summary

The BinaryReader class provides a convenient way to read primitive data types from a binary file or other data source. Its methods allow you to read various data types, including strings, from a stream. Remember to call the Close method when you're finished reading data to release any resources used by the BinaryReader.