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


I am working on a project on C #. I want to read a binary file of 64k in length, which is the only 16 bytes. Each 16 byte is a context in which the form is:

  #pragma noalign (trace_record) typedef struct trace_record {BYTE char tr_id [2]; // 2 byte WORD tr_task; // 2 byte word tr_process; // 2 byte WORD tr_varies; // 2 bytes KN_TIME_STRUCT tr_time; // 8 bytes} TRACE_RECORD;  

I think I can read the file using the binaryreader class, but how can I read this by multiplying 16 bytes in this form. Later, I will get some 16 byte marks for further processing. Therefore, I would be grateful for any help. Please assume that I'm getting started in C # :)

The easiest work example is below Probably though improvement can be done. If you have large endian data, you can use a library for example.

  public structure trace_record {// You can create an array here, but you can manually create a public byte tr_id_1; // 2 byte 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 & lt; Trace_record & gt; ReadRecords (string filename) {var results = new list & lt; Trace_record & gt; (); // StoreStream to FileStream (FileStream s = File.OpenRead (fileName)) and to check the current status using BinareReader (BinaryReader r = New BinaryReader (s)) {// Stop when file ends Reached (While .length; s.Length) {try {trace_record rec = new trace_record ()); Read the // or 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); } Hold {// handle the unexpected end of file in any way}} return result; }} Fixed zero main () {var results = Readers ("D: \\ in.txt"); // get all records by condition var filter = result Where (R = & gt; RTID_1 == 0x42); Console.ReadKey (); }  

Edit: Instead of using class instead of struct classes are more predictable, especially if you use C # Are new and the result will only reference the object in the list.


Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -