Thursday, April 12, 2007

Easiest way to Serialize/Deserialize in C#

string Serialize(object ObjectData)
{
MemoryStream stream = new MemoryStream();
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, ObjectData);
byte[] bArray;
bArray = stream.ToArray();
stream.Position = 0;
string tempobjectdatastring = Convert.ToBase64String(bArray);
stream.Close();
return tempobjectdatastring;

}
object DeSerialize(string datastring)
{
byte[] bArray;
bArray = Convert.FromBase64String(datastring);
MemoryStream stream = new MemoryStream();
stream.Position = 0;
stream.Write(bArray, 0, bArray.Length);
stream.Position = 0;
BinaryFormatter bformatter = new BinaryFormatter();
object tempobjectdata = bformatter.Deserialize(stream);
stream.Close();
return tempobjectdata;
}

No comments:

Post a Comment

Please, no abusive word, no spam.