struct MyStruct
{
int member1;
float member2;
int member3;
public void Read(BinaryReader reader)
{
member1 = reader.ReadInt32();
member2 = reader.ReadSingle();
member3 = reader.ReadInt32();
}
}
[.net] Struct from binary file
Hi guys, I recently tried to read a C# struct from a binary file. I was getting sick of having to do a BinaryReader.ReadMyType() for every member of the struct, so I searched the internet for alternatives.
I found this article on the subject.
The author concludes that although there are alternatives, reading the members like I did is the best way.
Therefore I'm now including a 'Read' function in all structs that have to be read from a file. It looks a bit like this:
I still have to write code to read each member, but it makes code that uses the struct a lot cleaner. Still, I'm not quite satisfied.
I would like to know what you guys are using to read your structs.
Have you considered using reflection to do the reading? You'd have to decide on some manner of sorting the public properties to keep them in the same order.
Another method would be to use generic serialization.
Another method would be to use generic serialization.
For reflection, you could do something like what I do. Basically,
The above being pseudocode, of course.
foreach(Field field in this.GetType().GetFields()){ field = read.ReadXXX(); ...}
The above being pseudocode, of course.
Also mind that if you try to use reflection you'll end up with similar limitations to what the XML serializer has (check MSDN for details).
IMHO the way you're doing it now is just fine. The only thing I'd add is to have your structs/classes implement an interface along the lines of this:
IMHO the way you're doing it now is just fine. The only thing I'd add is to have your structs/classes implement an interface along the lines of this:
public interface IMySerializable{ void Read(BinaryReader reader); void Write(BinaryWriter writer);}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement