19

How to serialize a rather complex structure into a byte[] array, using BinaryWriter?

Update:

  • For this to work, every structure (and sub-structure?) must be decorated with the [Serializable] attribute.

  • I do not need to implement the ISerializable interface, as this is designed to give an object control over its own serialization.

1
  • protobuf-net works perfectly (see the answer below). Highly recommended.
    – Contango
    Sep 19, 2011 at 10:52

3 Answers 3

34

Use the BinaryFormatter to serialize an object to a byte[]. BinaryWriter is just for writing bytes to a stream.

MyObject obj = new MyObject();
byte[] bytes;
IFormatter formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
   formatter.Serialize(stream, obj);
   bytes = stream.ToArray();
}
12
  • 2
    Absolutely brilliant. Just spent 2 hours on this, and you answered it in a few minutes. You are the Code King!!
    – Contango
    Sep 16, 2011 at 8:54
  • 2
    @Gravitas note that BinaryFormatter is tightly coupled to the type model; IMO it is suitable for transport between .NET and .NET apps of the exact same version, but it will run into lots of problems outside that tight window. Serialization is the answer here, but there are other serializers that behave much less badly than BinaryFormatter. Sep 16, 2011 at 8:56
  • 1
    @Gravitas re ToArray(), change to using (MemoryStream stream = ... Sep 16, 2011 at 9:09
  • 2
    Sorry updated, type stream to MemoryStream. Sep 16, 2011 at 9:11
  • 3
    @gdoron because it is tightly tied to the types (rather than an abstract schema), it has a long history of being brittle when people evolve their models - pretty much any kind of refactor (rename, move, change properties to automatically-implemented-properties, sign your assembly, change company name and thus assembly, etc) can cause massive problems. Then of course there's things like it doesn't exist in CoreCLR (and a range of other runtimes). I have lost count of the number of "help, I used BinaryFormatter and now I can't load my data any more" questions I've participated on. Too many. May 4, 2015 at 16:48
23

From comments, the OP's scenario requires strong compatibility with future versions of the application / .NET, in which case I always advise againt BinaryFormatter - it has many "features" that simply don't work well between versions (and certainly not between platforms).

I recommend looking at contract-based serializers; I'm biased, but I lean towards protobuf-net (which maps to Google's protobuf specification). The easiest way to do this is to attribute the types in such a way that the library can make light work of them (although it can also be done without attributes), for example:

 [ProtoContract]
 public class Customer {
     [ProtoMember(1)]
     public List<Order> Orders {get {....}}

     [ProtoMember(2)]
     public string Name {get;set;}

     ... etc
 }

(the attribute appoach is very familiar if you've done any XmlSerializer or DataContractSerializer work - and indeed protobuf-net can consume the attributes from those if you don't want to add protobuf-net specific attributes)

then something like:

Customer cust = ...
byte[] data;
using(var ms = new MemoryStream()) {
    Serializer.Serialize(ms, cust);
    data = ms.ToArray();
}

The data produced this way is platform independent, and could be loaded on any matching contract (it doesn't even need to be Customer - it could any type with matching layout via the attributes). Indeed, in most cases it'll load easily into any other protobuf implementation - Java, C++, etc.

6
  • @Gravitas - for info: code.google.com/p/support/issues/detail?id=5809 Sep 16, 2011 at 10:53
  • 2
    By the way, I've just integrated protobuf into my code, and it works beautifully. Looking at code base, it's a truly beautiful work of art. I swear am more impressed by truly elegant code than even the best examples of skill in the Louvre.
    – Contango
    Sep 19, 2011 at 10:51
  • 1
    @Gravitas you are overly generous; the internals are not particularly elegant (nor do they need to be). Library code often accepts a big chunk-o'-ugly so that the calling application code can be clean. See here for more Sep 19, 2011 at 10:55
  • @Contango +1 for vain but relate-ably depressing comment Oct 1, 2013 at 18:07
  • what about Version Tolerant Serialization ? msdn.microsoft.com/en-us/library/ms229752(v=vs.110).aspx
    – EKanadily
    Jun 3, 2015 at 19:43
8

code snippet.

public static byte[] XmlSerializeToByte<T>(T value) where T : class
{
    if (value == null)
    {
        throw new ArgumentNullException();
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (MemoryStream memoryStream = new MemoryStream())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream))
        {
            serializer.Serialize(xmlWriter, value);

            return memoryStream.ToArray();
        }
    }
}

    public static T XmlDeserializeFromBytes<T> (byte[] bytes)
                                     where T : class
    {
        if (bytes == null || bytes.Length == 0)
        {
            throw new InvalidOperationException();
        }

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        using (MemoryStream memoryStream = new MemoryStream(bytes))
        {
            using (XmlReader xmlReader = XmlReader.Create(memoryStream))
            {
                return (T)serializer.Deserialize(xmlReader);
            }
        }
    }


        //Serialize
        Duck duck = new Duck() { Name = "Donald Duck" };
        byte[] bytes = Test.XmlSerializeToByte(duck);
        //Deserialize
        var deDuck = Test.XmlDeserializeFromBytes<Duck>(bytes);
        Console.WriteLine(deDuck.Name);
2
  • how do we deserialize? Jul 3, 2015 at 6:14
  • 1
    @Jadoon updated answer, you could find how deserialize. Jul 3, 2015 at 8:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.