Serialization:
Converting
an object instance into a format that can either be stored to the disk or
transported over the network. Object
can be recreated with its current state at a different location.
How Serialization Works?
A
.NET formatter class must be used to control the serialization of the object to
and from the stream
The
serialized stream carries information about the objects type, including its
assembly name, culture & version
Role Of Formatters:
Determines
the serialization format for objects.
The
2 formatters that inherit from the IFormatter Interface are –
1. BinaryFormatter (Convert in Binary Format)
2. SOAPFormatter (Convert in XML Format)
Serializing Using SOAPFormatter:
Here we will discuss formatting with SOAPFormatter, you can easily do the BinaryFormatter just by replacing the SOAPFormatter into BinaryFormatter in Code:
- First make a assembly and add it into a Console Application, You can learn how to make a assembly here Use a DLL in C#.
- Make an object of the DLL in the Console Application, store values in object and Serialize it like the code given below.
Code for Serialization:
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
class Program
{
static void Main(string[] args)
{
tax t = new tax();
Console.WriteLine("Enter the %
of tax for salaray less than 2 Lacs?");
t.taxes[0, 1] = double.Parse(Console.ReadLine()); // storing values in object
Stream mystream = File.OpenWrite("serialized.ex"); // creating a file with .ex to serialize the object in
this file
SoapFormatter formatter = new SoapFormatter(); // object of SoapFormatter Class
formatter.Serialize(mystream,
t); //
serializing 't' object in file "mystream"
mystream.Close(); //
closing the .ex file
Console.WriteLine("Serialized");
}
}
Point to Remember:
Use [serializable] keyword with the class you want to serialize like given:
[Serializable]
public class tax
{
public double[,] taxes = new double[4, 2];
}
Code for Deserialization:
Deserialization is done on the machine where you want to use the data of serialized File, you can practice it in an application and show data there. First you have to add the DLL that you added in The Code is Given below:
private void button1_Click(object sender, EventArgs e)
{
SoapFormatter formatter = new SoapFormatter(); // object of SoapFormatter
Class
FileStream file = new FileStream(@"C:\\serialized.ex", FileMode.Open); //opening the .ex
file
tax t = formatter.Deserialize(file) as tax; // de formatting as object
t.taxes[0, 1] = 12; // now you can access data you stored while serializing
}
0 comments:
Post a Comment