Jump to content
  • Advertisement
Sign in to follow this  
Kalasjniekof

[.net] Struct from binary file

This topic is 4572 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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:
struct MyStruct
{
  int member1;
  float member2;
  int member3;
 
  public void Read(BinaryReader reader)
  {
    member1 = reader.ReadInt32();
    member2 = reader.ReadSingle();
    member3 = reader.ReadInt32();
  }
}



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.

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
For reflection, you could do something like what I do. Basically,


foreach(Field field in this.GetType().GetFields())
{
field = read.ReadXXX();
...
}



The above being pseudocode, of course.

Share this post


Link to post
Share on other sites
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:

public interface IMySerializable
{
void Read(BinaryReader reader);
void Write(BinaryWriter writer);
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!