[英]how to read binary file as a struct in c#?
我正在用C#开发一个项目。 我想读取一个长度为64k的二进制文件,该文件是16字节的倍数。 每个16字节是一个事件,其格式为:
#pragma noalign(trace_record)
typedef struct trace_record
{
BYTE char tr_id[2]; // 2 bytes
WORD tr_task; //2 bytes
WORD tr_process; //2 bytes
WORD tr_varies; //2 bytes
KN_TIME_STRUCT tr_time; //8 bytes
} TRACE_RECORD;
我想使用Binaryreader类,我可以读取文件,但是如何以这种形式通过16字节的倍数读取它。 稍后,我将提取一些16字节的迹线以进行进一步处理。 因此,感谢您的帮助。 请假设我是C#的初学者:)
下面是最简单的工作示例。 不过,它可能可以改进。 如果您有大端数据文件,则可以使用MiscUtil库。
public struct trace_record
{
// you can create array here, but you will need to create in manually
public byte tr_id_1; // 2 bytes
public byte tr_id_2;
public UInt16 tr_task; //2 bytes
public UInt16 tr_process; //2 bytes
public UInt16 tr_varies; //2 bytes
public UInt64 tr_time; //8 bytes
}
public static List<trace_record> ReadRecords(string fileName)
{
var result = new List<trace_record>();
// store FileStream to check current position
using (FileStream s = File.OpenRead(fileName))
// and BinareReader to read values
using (BinaryReader r = new BinaryReader(s))
{
// stop when reached the file end
while (s.Position < s.Length)
{
try
{
trace_record rec = new trace_record();
// or read two bytes and use an array instead of two separate bytes.
rec.tr_id_1 = r.ReadByte();
rec.tr_id_2 = r.ReadByte();
rec.tr_task = r.ReadUInt16();
rec.tr_process = r.ReadUInt16();
rec.tr_varies = r.ReadUInt16();
rec.tr_time = r.ReadUInt64();
result.Add(rec);
}
catch
{
// handle unexpected end of file somehow.
}
}
return result;
}
}
static void Main()
{
var result = ReadRecords("d:\\in.txt");
// get all records by condition
var filtered = result.Where(r => r.tr_id_1 == 0x42);
Console.ReadKey();
}
编辑:最好使用class
而不是struct
。 请参阅为什么可变结构“邪恶”? 类是更可预测的,特别是如果您不熟悉C#。 然后结果列表将仅存储对对象的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.