C# 读写二进制文件

632172d658a2cd9efe4a06e37f6d117c.png

读写二进制文件的一种选择是直接使用流类型;在这种情况下,最好使用字节数组执行读写操作。另一个选择是使用为这个场景定义的读取器和写入器:BinaryReader和BinaryWriter。使用它们的方式类似于使用 StreamReader 和 StreamWriter,但 BinaryReader 和 BinaryWriter 不使用任何编码。文件使用二进制格式而不是文本格式写入。

2c011cacf561c4096b9d4a705221da86.png

与 Stream 类型不同,BinaryWriter 为 Write() 方法定义了 18 个重载版本。重载版本接受不同的类型,如下面的代码片段所示,它写入 double、int、long 和string:

public static void WriteFileUsingBinaryWriter(string binFile)
{
  var outputStream = File.Create(binFile);
  using (var writer = new BinaryWriter(outputStream))
  {
    double d = 47.47; 
    int i = 42;
    long 1 = 987654321; 
    string s = "sample"; 
    writer.Write(d); 
    writer.Write(i); 
    writer.Write(1);
    writer.Write(s)
    }
  }

e8109750468f397b5ad1f776c4fcf684.png

为了再次读取文件,可以使用 BinaryReader。这个类定义的方法会读取所有不同的类型,如 ReadDouble、ReadInt32、ReadInt64 和 ReadString,如下所示:

public static void ReadFileUsingBinaryReader(string binFile) 
{
  var inputStream = File.Open(binFile, FileMode.Open); 
  using (var reader = new BinaryReader(inputStream))
  {
    double d = reader.ReadDouble(); 
    int i = reader.ReadInt32(); 
    long l = reader.ReadInt64();
    string s = reader.ReadString();
    Console.WriteLine($"d: {d}, i: {i},l: {1},s: {s}");
  }
}

33229754ad62e9b66aab301487ad5c62.png

读取文件的顺序必须完全匹配写入的顺序。创建自己的二进制格式时,需要知道存储的内容和方式,并用相应的方式读取。旧的微软 Word 文档使用二进制文件格式,而新的 docx 文件扩展是 ZIP 文件。

1c8b5a45aea4d254f798e1955ea7b058.png

392b31d1b5383f74b98a95d79dd648aa.png

 微信公众号 

Dotnet讲堂

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、付费专栏及课程。

余额充值