使用 BinaryWriter来写入二进制数据。 使用 BinaryReader来读取二进制数据。
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "malema.b");
using (var fileStream = File.OpenWrite(filePath)) //新版本两个using可以写在一起
using (var bw = new BinaryWriter(fileStream))
{
var buffer = new byte[] { 1, 2, 3, 4, 5, 6 };
bw.Write(buffer);
bw.Flush();
bw.Close();
}
using (var fileStream = File.OpenRead(filePath))
using (var br = new BinaryReader(fileStream))
{
var length = br.BaseStream.Length;
var bytes = br.ReadBytes((int)length); //如果文件很长这边是没有办法一次性全部读出来的。
Console.WriteLine(string.Join(",", bytes.Select(it => it.ToString())));
//输出 1,2,3,4,5,6
br.Close();
}
using (var fileStream = File.OpenRead(filePath))
using (var br = new BinaryReader(fileStream))
{
//跳到2的位置 开始读取
br.BaseStream.Seek(2, SeekOrigin.Begin);
var bytes = br.ReadBytes(4);
Console.WriteLine(string.Join(",", bytes.Select(it => it.ToString())));
//输出 3,4,5,6
br.Close();
}