Thursday, February 18, 2010

Serialize Objects using BinaryFormatter

Serialization is the process of converting an object to a format that can be transfer through a network or can be save to a location(file or DB).
The serialized data contains the object's informations like Version,Culture,PublicKeyToken,Type etc.
Deserialization is the reverse process of serialization, that is reconstructing the object from the serialized state to its original state.

Here is an eg:

A class "Employee" and its collection class "Employees". I marked these classes as Serializable with the [Serializable] attribute.
and also i am using BinaryFormatter to Serialize and Deserialize this object.



private void button1_Click
(object sender, EventArgs e)
{
Employees emps = new Employees();
emps.Add(new Employee("1", "Sabu"));
emps.Add(new Employee("2", "Litson"));

String pth = @"E:\Test.dat";
Serialize(emps, pth);
Deserialize(pth);
}

public void Serialize(Employees emps, String filename)
{
System.IO.Stream ms = File.OpenWrite(filename);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(ms, emps);
ms.Flush();
ms.Close();
ms.Dispose();
formatter = null;
}

public void Deserialize(String filename)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
object obj = formatter.Deserialize(File.Open(filename, FileMode.Open));
Employees emps = (Employees)obj;
MessageBox.Show(emps[1].Name);
}


//Classes
[Serializable]
public class Employee
{

public Employee(String id, String name)
{
_ID = id;
_Name = name;
}

private String _ID = String.Empty;
private String _Name = String.Empty;

public String ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}

public String Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
}

[Serializable]
public class Employees:CollectionBase
{
//Constructor
public Employees()
{

}

//Add function
public void Add(T objT)
{
this.List.Add(objT);
}

//Indexer
public T this[int i]
{
get
{
return (T) this.List[i];
}
set
{
this.List.Add(value);
}
}
}

No comments:

Post a Comment