Gabriel Sanmartin Gabriel Sanmartin - 21 days ago 6
C# Question

How to read byte blocks into struct

I have this resource file which I need to process, wich packs a set of files.

First, the resource file lists all the files contained within, plus some other data, such as in this struct:

struct FileEntry{
byte Value1;
char Filename[12];
byte Value2;
byte FileOffset[3];
float whatever;
}


So I would need to read blocks exactly this size.

I am using the Read function from FileStream, but how can I specify the size of the struct?
I used:

int sizeToRead = Marshal.SizeOf(typeof(Header));


and then pass this value to Read, but then I can only read a set of byte[] which I do not know how to convert into the specified values (well I do know how to get the single byte values... but not the rest of them).

Also I need to specify an unsafe context which I don't know whether it's correct or not...

It seems to me that reading byte streams is tougher than I thought in .NET :)

Thanks!

Answer

Assuming this is C#, I woudn't create a struct as a FileEntry type. I would replace char[20] with strings and use a BinaryReader - http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx to read individual fields. You must read the data in the same order as it was written.

Something like:

class FileEntry {
     byte Value1;
     char[] Filename;
     byte Value2;
     byte[] FileOffset;
     float whatever;
}

  using (var reader = new BinaryReader(File.OpenRead("path")) {
     var entry = new FileEntry {
        Value1 = reader.ReadByte(),
        Filename = reader.ReadChars(12) // would replace this with string
        FileOffset = reader.ReadBytes(3),
        whatever = reader.ReadFloat()           
     };
  }

If you insist having a struct, you should make your struct immutable and create a constructor with arguments for each of your field