高手救命 c#中如何读取二进制结构体文件?

bmoon 2008-03-12 09:52:36
高手救命 c#中如何读取二进制结构体文件:
文件结构体中有 :
unsigned short int Size;
char ID;
char Type;
short int IDS;
unsigned short int Date;
等数据类型
请问该怎么读取呀,小弟刚接触c#,求高手救命呀 。。。。
...全文
383 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
xue12300 2010-07-14
  • 打赏
  • 举报
回复
怎么解决的,说一下吧
hbdn520 2009-02-13
  • 打赏
  • 举报
回复
高手
林g 2008-03-13
  • 打赏
  • 举报
回复
高手!
fuda_1985 2008-03-13
  • 打赏
  • 举报
回复
kmar
bmoon 2008-03-13
  • 打赏
  • 举报
回复
已经解决了,谢谢:) 非常感谢各位
Gao_TF 2008-03-13
  • 打赏
  • 举报
回复
采用二进制文件方式一个字节一个字节读,看看这样成不成

/// <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();

}
bmoon 2008-03-13
  • 打赏
  • 举报
回复
原来的结构是这样的 :
typedef struct{
unsigned short int head[6];
unsigned short int Size;
char ID;
char Type;
short int IDS;
unsigned short int Date;
}DATAP;

我已经把它转换为c#里面的不安全结构体了
如下:
public unsafe struct DATAPACKET
{
public fixed ushort head[6];
public ushort Size;
public byte ID;
public byte Type;
public short IDS;
public ushort Date;
}

可是下面怎么做呢:?已经知道这个结构体的字节长度,和整个文件的长度。
恳请高手给我这个菜鸟一点代码级的指点,谢谢救命啊。。。。
真相重于对错 2008-03-12
  • 打赏
  • 举报
回复
structlayout
marshal.Ptrtostructure
chenjx00 2008-03-12
  • 打赏
  • 举报
回复
定义结构,用不安全代码.
ericzhangbo1982111 2008-03-12
  • 打赏
  • 举报
回复
如果文件有各式的话还可以。

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧