`
dazhilao
  • 浏览: 240452 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

c#中读取二进制结构体文件

阅读更多
文件结构体中有 :
unsigned short int Size; 
char ID;  
char Type; 
short int IDS;  
unsigned short int Date; 


采用二进制文件方式一个字节一个字节读,看看这样成不成  

/// <summary>
  /// 读取二进制文件
  /// </summary>
  /// <param name="fileName">文件名</param>
  public void ReadMyBinaryFile(string fileName)
  {
  FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  /*
  * public unsafe struct DATAPACKET
  {
  public fixed ushort head[6];
  public ushort Size;  
  public byte ID;  
  public byte Type; 
  public short IDS; 
  public ushort Date;
  } 
  */
  int iFileLength = fileStream.Length;//文件长度
  int iStructLength = 20;//结构体的字节长度
  int iTimes = iFileLength / iStructLength;//共有多少个字节

  DATAPACKET tmp;
  byte[] byTmp = new byte[2];

  for (int i = 0; i < iTimes; i++)
  {
  //读头部六个短整型字节
  for (int j = 0; j < 6; j++)
  {
  if (fileStream.Read(byTmp, 0, 2) != 2)
  {
  Console.WriteLine("file read error!");
  return;
  }
  tmp.head[j] = BitConverter.ToUInt16(byTmp, 0);
  }
  //读大小
  if (fileStream.Read(byTmp, 0, 2) != 2)
  {
  Console.WriteLine("file read error!");
  return;
  }
  tmp.Size= BitConverter.ToUInt16(byTmp, 0);
  //读id
  tmp.ID = fileStream.ReadByte();
  //读类型
  tmp.Type = fileStream.ReadByte();
  //读ids
  if (fileStream.Read(byTmp, 0, 2) != 2)
  {
  Console.WriteLine("file read error!");
  return;
  }
  tmp.IDS = BitConverter.ToInt16(byTmp, 0);
  //读日期
  if (fileStream.Read(byTmp, 0, 2) != 2)
  {
  Console.WriteLine("file read error!");
  return;
  }
  tmp.Date = BitConverter.ToUInt16(byTmp, 0);
  /*
  .........对读出变量进行处理
  */

  }
  /*
  .....后续处理
  */
  fileStream.Close();

  }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics