Ok, so I currently have a binary file containing an unknown number of structs like this:
private struct sTestStruct
{
public int numberOne;
public int numberTwo;
public int[] numbers; // This is ALWAYS 128 ints long.
public bool trueFalse;
}
So far, I use the following to read all the structs into a List<>:
List<sTestStruct> structList = new List<sTestStruct>();
while (binReader.BaseStream.Position < binReader.BaseStream.Length)
{
sTestStruct temp = new sTestStruct();
temp.numberOne = binReader.ReadInt32();
temp.numberTwo = binReader.ReadInt32();
temp.numbers = new int[128];
for (int i = 0; i < temp.numbers.Length; i++)
{
temp.numbers[i] = binReader.ReadInt32();
}
temp.trueFalse = binReader.ReadBoolean();
// Add to List<>
structList.Add(temp);
}
I don’t really want to do this, as only one of the structs can be displayed to the user at once, so there is no point reading in more than one record at a time. So I thought that I could read in a specific record using something like:
fileStream.Seek(sizeof(sTestStruct) * index, SeekOrigin.Begin);
But it wont let me as it doesn’t know the size of the sTestStruct, the structure wont let me predefine the array size, so how do I go about this??
The
sTestStructis not stored in one consecutive are of memory andsizeof(sTestStruct)is not directly related to the size of the records in the file. Thenumbersmembers is a reference to an array which you allocate youself in your reading code.But you can easily specify the record size in code since it is a constant value. This code will seek to the record at
index. You can then read one record using the body of your loop.If you have many different fixed sized records and you are afraid that manually entering the record size for each record is error prone you could devise a scheme based on reflection and custom attributes.
Create an attribute to define the size of arrays:
Use the attribute on your record type:
You can then compute the size of the record using this sample code:
Use it like this:
You will probably have to expand a little on this code to use it in production.