Personally I'd use BinaryReader
here. The reason being that it allows you to define one set of types to represent these structures, that feels clean in C#. If you were to use Marshal.PtrToStructure
then you are compelled to define interop types that feel clunky in C#.
You state that the structs are packed which is good. Aligned structures makes life harder because you have to understand how the compiler laid out the structures. For storing to disk, aligned structures should generally be avoided.
I would perhaps define types like this:
public struct Row
{
public uint id;
public string name;
}
public struct Page
{
public uint prev;
public uint next;
public Row[] items;
}
You could use classes if you prefer. Or List<Row>
. It's really up to you.
Then read the file with a method like this:
public static Page ReadPage(BinaryReader reader)
{
Page page;
page.prev = reader.ReadUInt32();
page.next = reader.ReadUInt32();
ushort count = reader.ReadUInt16();
page.items = new Row[count];
for (int i=0; i<count; i++)
{
page.items[i].id = reader.ReadUInt32();
page.items[i].name = Encoding.ASCII.GetString(reader.ReadBytes(256));
}
// skip past the unused rows
reader.ReadBytes((256+sizeof(uint))*(256-count));
}
I've assumed ASCII encoding. But perhaps it is UTF-8 or ANSI. I assume that the strings are null-terminated, but have not actually coded any null-terminator detection. I'm hoping you'll be able to do that!
ItemCount
andItem
. I also suspect that what is stored to the file will not necessarily contain all 256ROW
items. I guess it will contain onlyItemCount
of them. I'd say you need to choose betweenMarshal.PtrToStructure
andBinaryReader
. Which do you prefer? Do you know the answers to any of these questions?BinaryReader
here. The reason beingPtrToStructure
involves creating struct types that are only useful when reading the file. In your C# code you'll likely want aRow
struct and aPage
class that contains aList<Row>
. Would you like me to show you some outline code on that basis?