[英]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.