Monday, May 6, 2013

BinaryFormatter Serialization in CSharp (C#)


Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file.Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization. Once its serialized we can use it anywhere by using Deserialization. Here we can see a sample that serialize an object into binary format file.
We have to specify the Serializable() above the class that is to be used as object like below.

C# Code:
[Serializable()]  
public class calc  
{  
    public string a;  
    public string b;  
    public string c;  
}  

Serialization:

Here we converting an object into binary format file.

calc c = new calc();  
c.a = "10";  
c.c = "20";  
c.b = "30";  
BinaryFormatter bfo = new BinaryFormatter();  
FileStream fs = new FileStream("c:\\file.dat", System.IO.FileMode.Create);  
bfo.Serialize(fs, c);  
fs.Close();  

Deserialization:

Here we converting back from the binary format file to the object.

calc c1 = new calc();     
BinaryFormatter bfo = new BinaryFormatter();  
FileStream fs = new FileStream("c:\\file.dat", System.IO.FileMode.Open);  
c1=(calc)bfo.Deserialize(fs);  
fs.Close();  
Console.WriteLine(c1.a);