My original goal is to serialize Listusing System.Runtime.Serialization.Formatters.Binary;
Here is how to use:
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);
}
}//prepare the object
You can replace the MemoryStream by other Stream classes.
List<int> lstInteger = new List<int>(3) {1, 2, 3};
//serialize object
string strResult = SerializeObject(lstInteger);
//deserialize object
List<int> lstResult = DeSerializeObject(strResult);
Serialize/Deserialize object to binary format
Subscribe to:
Post Comments (Atom)

0 Comments:
Post a Comment