[.net] Struct from binary file

Started by
4 comments, last by Kalasjniekof 18 years, 3 months ago
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.
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.
tnx for the link. How would reflection work here?
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.
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);}
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose, so let me simply add that it's my very good honor to meet you and you may call me V.".....V
Tnx for your opinions, I think I'll use joanusdmentia's method as it is the one I understand best.

This topic is closed to new replies.

Advertisement