Sign in to follow this  

[.net] Struct from binary file

This topic is 4358 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
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

This topic is 4358 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this