如何在c#中读取二进制文件作为结构?

时间:2014-08-01 10:16:24

标签: c# struct

我正在研究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#的初学者:)

1 个答案:

答案 0 :(得分:0)

最简单的工作示例如下。它可能会改善。如果您有大端数据i文件,则可以使用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可能更好。请参阅Why are mutable structs “evil”?类更易于预测,特别是如果您不熟悉C#。然后结果列表将仅存储对象的引用。