C# 读取2进制文件(bin文件)

读取2进制文件采用下列方式

using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open)))
{
 long fileLength = reader.BaseStream.Length; // 获取文件长度
 byte[] data = reader.ReadBytes(400);  //读取文件中前400个字节
}

C#中,读写二进制文件流通常涉及到对字节数据的操作,这在处理图像、音频等非文本文件时非常有用。C#提供了一系列内置的类来帮助完成这样的任务,主要包括`System.IO.BinaryReader` 和 `System.IO.BinaryWriter`。 ### 1. 使用BinaryReader读取二进制文件 `BinaryReader`类允许您从二进制文件读取各种类型的值,如整数、浮点数和字符串。以下是一个简单的示例: ```csharp using System; using System.IO; class Program { static void Main() { string filePath = "example.bin"; // 文件路径 using (FileStream fs = new FileStream(filePath, FileMode.Open)) { BinaryReader br = new BinaryReader(fs); int number = br.ReadInt32(); // 读取4字节整数 float floatNumber = br.ReadSingle(); // 读取4字节浮点数 byte[] dataBytes = br.ReadBytes(5); // 读取5个字节 Console.WriteLine($"Read integer: {number}"); Console.WriteLine($"Read single: {floatNumber}"); Console.WriteLine("Data bytes read:"); foreach(byte b in dataBytes) { Console.Write($"{b} "); } } } } ``` ### 2. 使用BinaryWriter写入二进制文件 同样地,`BinaryWriter`类可以用于将不同类型的数据写入到二进制文件中: ```csharp using System; using System.IO; class Program { static void Main() { string filePath = "output.bin"; using (FileStream fs = new FileStream(filePath, FileMode.Create)) { BinaryWriter bw = new BinaryWriter(fs); bw.Write(10); // 写入一个整数 bw.Write(3.14f); // 写入一个浮点数 bw.Write(new byte[]{1, 2, 3}); // 写入一组字节 Console.WriteLine("Data written to file."); } } } ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值