Tuesday, November 18, 2008

Serialization in .NET

Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is deserialization, which converts a stream into an object. Together, these processes allow data to be easily stored and transferred. There are two types binary serialization and xml serialization. here is the example of binary serialization.

// Serialization
public byte[] getByteArrayWithObject(object o)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(ms, o);
return ms.ToArray();
}

// deserilization
private Object getObjectWithByteArray(byte[] arrBytes)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
Object obj = (Object)binForm.Deserialize(memStream);
return obj;
}

No comments: