Serialization can be defined as the process of converting the state of an object instance to a stream of data, so that it can be transported across the network or can be persisted in the storage location. 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 state of an object to a storage medium so an exact copy can be recreated at a later stage. Deserialization is its reverse process, that is unpacking stream of bytes to their original form.
Any attempt to pass the object as a parameter or return it as a result will fail unless the object derives from MarshalByRefObject. This process of serializing an object is also called deflating or marshalling an object. If the object is marshalling or it is marked as Serializable, the object will automatically be serialized.
The following program will show how to Serialize an Object and later De-serialize it.
using System;
using System.IO ;
using System.Windows.Forms;
using System.Runtime.Serialization;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//serializing the object
private void button1_Click(object sender, EventArgs e)
{
serializeObject srObj = new serializeObject();
srObj.srString = ".Net serialization test !!";
srObj.srInt = 1000;
IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Stream fileStream = new FileStream("c:\\SerializeFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(fileStream, srObj);
fileStream.Close();
MessageBox.Show("Object Serialized !!");
}
//de-serializing the object
private void button2_Click(object sender, EventArgs e)
{
IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Stream serialStream = new FileStream("c:\\SerializeFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
serializeObject srObj = (serializeObject)formatter.Deserialize(serialStream);
serialStream.Close();
MessageBox.Show(srObj.srString + " " + srObj.srInt.ToString ());
}
}
//specimen class for serialization
[Serializable]
public class serializeObject
{
public string srString = null;
public int srInt = 0;
}
}
No comments:
Post a Comment