C#读取二进制字节流

1、以下方法将一个对象序列化为可以在数据库中存储的字节数组
private byte[] getByteData(SupplementData data)
  {
   BinaryFormatter serializer =new BinaryFormatter();
   MemoryStream memStream =new MemoryStream();
   serializer.Serialize(memStream,data);
   int length = (int)memStream.Length;
   byte[] buffer = new byte[length];
   memStream.Position = 0;
   memStream.Read(buffer,0,length);
   return buffer;
  }
调用方法得到字节数组后给参数赋值:
oCommand.Parameters[5].Value =getByteData(OldData);
2、以上是关于序列化后的字节数组的存储,那读取呢?

  private SupplementData GetHistoryData(string Track_UUID)
  {
   //根据ID得到一笔记录,GetTable是本人系统中的特定方法
   DataTable table = GetTable("LIC_DATA_TRACK","TRACK_UUID",Track_UUID,out sErrorMsg);

   BinaryFormatter deserializer =new BinaryFormatter();
   MemoryStream stream =new MemoryStream();
   //将得到的记录中的某个Bolb类型的数据读出来存储到数据流中
   byte[] objBytes =(byte[])table.Rows[0]["HistoryData"];
 
  stream.Write(objBytes,0,objBytes.Length);
   stream.Position = 0;
   //字节流反序列化后,返回对象SupplementData(本人定义的一个对象)
   return (SupplementData)deserializer.Deserialize(stream);
  }

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
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."); } } } ``` ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值