简体   繁体   中英

how to read binary file as a struct in c#?

I am working on a project in c#. i want to read a binary file of 64k in length which is multiple of 16 bytes. each 16 byte is an event which has the form:

#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;

i guess using Binaryreader class i can read the file but how to read it by multiples of 16 byte in this form. later i will extract some 16 byte traces for further processing. so I will be thankful for any help. please assume i am beginner in c# :)

The simplest working example is below. It can probably be improved though. If you have big-endian data i file, you can use a MiscUtil library for example.

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

EDIT: it's probably better to use class instead of struct . See Why are mutable structs “evil”? Classes are more predictable, especially if you are new to C#. And result list will then store only references to objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM