2009/07/15

Serialize/Deserialize object to/from binary format

My original goal is to serialize List and List object, but I believe this method can be applied to other data types.
using System.Runtime.Serialization.Formatters.Binary;

public static string SerializeObject(object data)
{
    BinaryFormatter formatter = new BinaryFormatter();
    using (MemoryStream ms = new MemoryStream())
    {
        //this is the key: serialize
        formatter.Serialize(ms, data);

        using (TextReader tr = new StreamReader(ms))
        {
            //set the position
            ms.Seek(0, SeekOrigin.Begin);
            return tr.ReadToEnd();
        }
    }
}

public static object DeSerializeObject(string data)
{
    BinaryFormatter formatter = new BinaryFormatter();
    using (MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(data)))
    {
        //set the position
        ms.Seek(0, SeekOrigin.Begin);
        return formatter.Deserialize(ms);
    }
}
Here is how to use: