जगदीश खोलिया: Serialization in .net

Friday, May 25, 2012

Serialization in .net

Serialization is a process of converting an object into a stream of data so that it can be easily transmittable over the network or can be continued in a persistent storage location.  This storage location can be a physical file, database or ASP.NET Cache.  Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines.  This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed easily.  The advantage of serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent storage medium in a non-proprietary format.  Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client.  De-serialization is the reverse; it is the process of reconstructing the same object later.  The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another.
Serialization is a process by which we can save the state of the object by converting the object in to stream of bytes.These bytes can then be stored in database, files, memory etc.

Below is a simple code of serializing the object.

MyObject objObject = new MyObject();

objObject.Value = 100;
// Serialization using SoapFormatter

SoapFormatter formatter = new SoapFormatter();

Stream objFileStream = new FileStream("c:\\MyFile.xml", FileMode.Create,
FileAccess.Write, FileShare.None);

formatter.Serialize(objFileStream, objObject);

objFileStream.Close();

Below is simple code which shows how to deserialize an object.

//De-Serialization

Stream objNewFileStream = new FileStream("c:\\MyFile.xml", FileMode.Open,
FileAccess.Read, FileShare.Read);

MyObject objObject =(MyObject)formatter.Deserialize(objNewFileStream);

objNewFileStream.Close();
Post a Comment