Serialize/Deserialize object to binary format

My original goal is to serialize List and List object, but I believe this method can be applied to other type of objects.

using System.Runtime.Serialization.Formatters.Binary;

public 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.

0 Comments:

Random Posts

Powered by Stuff-a-Blog