जगदीश खोलिया: Serialization and Deserialization

Friday, June 1, 2012

Serialization and Deserialization

Serialization: -“Serialization” is a process of converting an object into a stream of bytes.

Deserialization: – “Deserialization” is reverse of “serialization”, where stream of bytes are converted back in to an object.
Let’s see a simple example how exactly we can do “serialization” and
“deserialization”.
It’s very simple four steps procedure as follows.
Step1: – create a new “window application” like below diagram.

Step2: – Now create a customer class in “Form1.cs” file.
[Serializable]
public class Customer
{
public string CustomerCode;
public string CustomerName;
}
Step3: – Now, we will see how exactly “serialization” is done.
Import the following namespace 
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

private void Serialize_Click(object sender, EventArgs e)
{
Customer obj = new Customer();// created instance of the customer class
obj.CustomerCode = textBox1.Text;
obj.CustomerName = textBox2.Text;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("E:\\Customer.bin", FileMode.Create,
 FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
textBox1.Text = "";
textBox2.Text = "";
}
Step4: – Similarly, we will do for “deserialization”.
private void Deserialize_Click(object sender, EventArgs e)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("E:\\Customer.bin", FileMode.Open, 
FileAccess.Read, FileShare.Read);
Customer obj = (Customer)formatter.Deserialize(stream);
stream.Close();
textBox1.Text = obj.CustomerCode;
textBox2.Text = obj.CustomerName;
}

No comments: