阅读量:2
在C#中,使用BinaryReader类可以方便地读取二进制文件中的数据。以下是一个简单的示例,展示了如何使用BinaryReader读取不同类型的数据:
using System;
using System.IO;
class Program
{
static void Main()
{
// 替换为您的文件路径
string filePath = "path/to/your/binaryfile.bin";
// 使用FileStream打开文件
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// 创建一个BinaryReader实例
using (BinaryReader binaryReader = new BinaryReader(fileStream))
{
// 读取整数
int integerValue = binaryReader.ReadInt32();
Console.WriteLine("Integer value: " + integerValue);
// 读取浮点数
float floatValue = binaryReader.ReadSingle();
Console.WriteLine("Float value: " + floatValue);
// 读取字符串(假设字符串长度为固定值)
int stringLength = binaryReader.ReadInt32();
string stringValue = binaryReader.ReadString(stringLength);
Console.WriteLine("String value: " + stringValue);
// 跳过字节(例如:跳过4个字节)
binaryReader.ReadBytes(4);
// 读取布尔值
bool booleanValue = binaryReader.ReadBoolean();
Console.WriteLine("Boolean value: " + booleanValue);
}
}
}
}
在这个示例中,我们首先使用FileStream打开一个二进制文件,然后创建一个BinaryReader实例。接下来,我们使用BinaryReader的方法读取不同类型的数据,如整数、浮点数、字符串、字节和布尔值。注意,在读取字符串之前,我们需要先读取字符串的长度。在读取字节之后,我们使用ReadBytes方法跳过指定数量的字节。
以上就是关于“c# binaryreader如何读取数据”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm