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:
//prepare the object
List<int> lstInteger = new List<int>(3) {1, 2, 3};
//serialize object
string strResult = SerializeObject(lstInteger);
//deserialize object
List<int> lstResult = DeSerializeObject(strResult);
You can replace the MemoryStream by other Stream classes.

PS: You will get an error message if you try to use DataTable.

No comments:

Post a Comment