Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a file containing binary data with a format that matches this struct:

struct MyStruct {
    UInt32 count;
    UInt32[] items;
}

The binary data can be any length as there can be any number of items, but the number of items is defined in count. Using Marshal.PtrToStructure doesn't seem to allow for this binary format, where there is a variable number of items? Using Attributes you can set the size of the array of items, but this has to be a constant, is there no way to tell it to look in count while its reading the data?

I've thought of defining the format in XML, and using it to read into the struct with my own code, but this would be a lot of duplicate data, if the file format changed, I'd have to change the XML and struct, rather than just the struct.

And I've thought of using a custom Attribute on the items field, and writing my own code to read in the data but in order to enumerate through the struct's fields I'd have to use Reflection? which is slow?

(Also I could read it myself manually, but I've trimmed the struct down for the question, and like to not have to change the reading code if the structure changes)

share|improve this question
I'm presuming you want to avoid XML due to its extra overhead (in parsing, and in filesize); parsing an XML file containing 10000 of these MyStruct can be done in a single line: List<MyStruct> data = (List<MyStruct>) new XmlSerializer(typeof(List<MyStruct>)).Deserialize(File.OpenText("MyStructs.xml")‌​); – Mr. Smith Apr 21 at 0:59
The data is a preexisting binary file, I have no control how the data is stored. – Jonathan. Apr 21 at 1:32

1 Answer

Use .Read() method on an instance of Stream, reading into a byte[], then use System.BitConverter.ToUInt32(bytearray, startindex) to get your binary data into uint32 form.

share|improve this answer
I'm not having trouble reading the data, it's how I read the data in a way that reduces information duplication, isn't slow and doesn't require changes to the code that reads that data if the format changes. – Jonathan. Apr 20 at 20:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.