Tuesday, May 7, 2013

XmlSerializer 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 XML format file.
 public class calculation  
 {  
     public string Name{ get; set; }  
     public string Age { get; set; }   
 }  

Serialization:
Here we converting an object into XML format file.

 calculation cal = new calculation();  
 cal.Name = "Venkadesh";  
 cal.Age = "21";  
 System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(calculation));  
 System.IO.StreamWriter swriter = new System.IO.StreamWriter(@"e:\CalculationObject.xml");  
 serializer.Serialize(swriter, cal);  
 swriter.Close();  

Deserialization:
Here we converting back from the XML format file to the object.

 
 calculation cal1 = new calculation();   
 System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(calculation));  
 System.IO.StreamReader sreader = new System.IO.StreamReader(@"e:\CalculationObject.xml");  
 cal1 = (calculation)serializer.Deserialize(sreader);  
 sreader.Close();  
 Console.WriteLine(cal1.Name);  
 Console.WriteLine(cal1.Age);  

No comments:

Post a Comment