Serialize non-primitive objects using BinaryWriter

232 Views Asked by At

I would like to use the System.IO.BinaryWriter to serialize data structure with non-primitive fields\properties. I know that this serializer can work only with primitive types, so I need to "dig-in" into each object. I assumed that the BinaryWriter is a reference value and can be passed, but it seems like this is not the correct way of doing so. How do the Serialize function should be ?

This is my code:

public Enum SomeType
{
    regular = 1,
    special =2
}
public class MessageHeader
{
    public SomeType messagetype {get; set;}
    public double MsgTime {get; set;}
    public long MsgSize {get; set;}

    public void Serialize(BinaryWriter bw)
    {
        bw.Write ((int)messagetype);
        bw.Write (MsgTime);
        bw.Wrtie(MsgSize);
    }

    public class Message
    {
        public MessageHeader Header {get; set;}
        public string body {get; set;}
        public void Serialize()
        {
            MemoryStream ms= new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms, Encoding.Unicode/*or Utf8*/)
            Header.Serialize(bw); 
            Serialize(bw);
            Byte[] bArray = ms.ToArray();
        }

    }
0

There are 0 best solutions below