I'm reading in a binary file, and I would like to know the number of elements of a custom object, the binary file contains (which makes searching for the EOF with size useless, because its all about the number of elements).
This is what I'm doing right now:
using (var stream = File.OpenRead(openDialog.FileName))
using (var reader = new BinaryReader(stream))
{
while (CustObject.ReadFromBinaryReader(reader) != null)
{
objList.Add(CustObject.ReadFromBinaryReader(reader));
}
}
For some reason though, this doesn't work. I get the error: Unable to read beyond end of stream.
So instead, I would like to find out how many elements there are in the binary file, and use that count to read in all the objects into the object list.
Another method I thought of using, was writing into the file how many elements there are when I write the binary file.
binaryWriter.Write(string.Format("{0}", objList.Count()));
However, I don't know how I would read in just that number, so I think the for
loop is the best option.
while (CustObject.ReadFromBinaryReader(reader) != null)
{
objList.Add(CustObject.ReadFromBinaryReader(reader));
}
Your problem happens because probably when you read last item in while condition, you read once again afterwards.
Write number of elements in the beginning of file, say as integer, then read that single byte first of all. Check sample here how to write integer to file. Then read this integer back first, and continue with reading your objects.
Or if you know exactly how many bytes your objects takes up in file (if it has fixed size), divide file size by this number?