Serialization in C# and .NET

Serialization

XML Serialization

Object Serialization is a process through which an object's state is transformed into some serial data format, such as XML or binary format, in order to be stored for some later use. In other words, the object is "dehydrated" and put away until we need to use it again.

Some good uses for serialization/deserialization include: 

  1. Storing user preferences in an object.
  2. Maintaining security information across pages and applications.
  3. Modification of XML documents without using the DOM.
  4. Passing an object from on application to another.
  5. Passing an object from one domain to another.
  6. Passing an object through a firewall as an XML string. 

XML Serialization: It is limited that it can serialize only public members.

Required Namespace :

using System.Xml;
using System.Xml.Serialization;

Create XSD file from Class

Object instance into XML file

Create one web project and add Person.cs class file.

using System;
using System.Xml;
using System.Xml.Serialization;
namespace XMLSerialization
{
    /// <summary>
    /// Summary description for Person.
    /// </summary>
    [XmlRoot("Class_Person")]
    public class Person
    {
        private string m_sName;
        private int m_iAge;
        public Person()
        {}
        [XmlElement("Property_Name")]
        public string Name
        {
            get {return m_sName;}
            set {m_sName=value;}
        }
        [XmlElement("Property_Age")]
        public int Age
        {
            get{return m_iAge;}
            set{m_iAge=value;}
        }
        public string Hello()
        {
            return "Hi! My name is " + Name + " and I am " + Age.ToString() + " years old";
        }
        public string GoodBye()
        {
            return "So long";
        }
    }
}

[XMLRoot()] and [XMLElement()] these are the .net attributes and tell the serializer where the various members of this object will appear in the XML document and what they will be named. Without these, serialization cannot take place.

XmlSerializer objXmlSer = new XmlSerializer(typeof(Person));
Person objLucky = new Person();
StreamWriter objStrWrt;
objLucky.Name = "Myname";
objLucky.Age = 30;
Response.Write(objLucky.Hello());
Response.Write(objLucky.GoodBye());
objStrWrt = new StreamWriter(Server.MapPath("abc.xml"));
objXmlSer.Serialize(objStrWrt,objLucky);
objStrWrt.Close();

First of all, we declare and instantiate an XMLSerializer object. The typeof() function describes what type of object it's going to be serializing. Then we assign Name and Age properties of the Person object. Then we used to see the output of that object by calling Hello() and GoodBye() functions. Then we initiates a StreamWriter object and that it will be writing to a file call abc.xml. We then call the Serialize() method of the XMLSerializer object and send it our person object to be serialized as well as the StreamWriter object so it will write the resulting XML to the file specified. Then we close the StreamWriter.

The Abc.Xml file is look like.

<Xml version="1.0" encoding="utf-8" ?>
 <Class_Person xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Property_Name>TestProperty1 </Property_Name>
  <Property_Age>30</Property_Age>
  </Class_Person>

Create class object from XML file:

XML file into Object instance.

Now, make some changes in your abc.xml file.

<xml version="1.0" encoding="utf-8" ?>
<Class_Person xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance">
 <Property_Name>TestProperty2</Property_Name> 
  <Property_Age>32</Property_Age> 
  </Class_Person>

First create instance of Person class. Next, we create an instance of StreamReader object and feed it the stored XML file. Then we instantiate the Person object by calling the deserialize() method of the XMLSerializer object. This method use the StreamReader object to read the content of the XML file. You have to explicitly casting the type to Person type.

Person objDesPerson = new Person();
StreamReader objStrRdr;
objStrRdr = new StreamReader(Server.MapPath("abc.xml"));
XmlSerializer objXmlSer = new XmlSerializer(typeof(Person));
objDesPerson = (Person)objXmlSer.Deserialize(objStrRdr);
Response.Write(objDesPerson.Name);
Response.Write(objDesPerson.Age.ToString());
objStrRdr.Close(); 

Binary Serialization

public class Article
{
    public string sTitle;
    public string sAuthor;
    public string sText;
}

Not much to this class, just a few string variables. Lets suppose that we need to write an instance of this call tout to disk. To do this, we can use binary serialization. This will create a binary file that can be read back in as an instance of Article. To do this, we will need to implement 2 methods GetObjectData and Overloaded Constructor.

It will requires following namespace:

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

First we will make the class with serializable attribute and implements the ISerializable interface.

[Serializable()]

public class Articles :ISerializable

We have to implements GetObjectData method of ISerializable interface.

public void GetObjectData(SerializationInfo info, StreamingContext context)
{
    info.AddValue("Title", sTitle);
    info.AddValue("Author", sAuthor);
    info.AddValue("Text", sText);
}

This method will allow you to serialize the objects to disk. We could add any code in here that we wanted to customize the way the data is serialized.

Now we need a method to retrieve the data from a serialized object then we will use a overloaded constructor for this.

public Articles(SerializationInfo info,StreamingContext context)
{
    sTitle =Convert.ToString(info.GetValue("Title",typeof(String)));
    sAuthor = Convert.ToString(info.GetValue("Author",typeof(String)));
    sText = Convert.ToString(info.GetValue("Text",typeof(String)));
}

The empty constructor is added here so that you can create a new Article object without deserialized one.

Now we have a class that can be serialized and deserialized. For serializing this class we have to create methods like

Serializing the object 

public void serialize(string fileName)
{
    FileStream s = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
    BinaryFormatter B = new BinaryFormatter();
    B.Serialize(s, this);
    s.Close();
}

Here first we create an instance of FileStream class which, will create file and open it in read and write mode. Next we create an instance of BinaryForamtter class. This class have Seralize method which take parameters FileStream and Instance which you want to serialize.

DeSerializing the object 

public Articles deSerialize(string fileName)
{
    FileStream Fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    BinaryFormatter F = new BinaryFormatter();
    Articles s1 = (Articles)F.Deserialize(Fs);
    Fs.Close();
    return s1;
}

Here again create an instance of BinaryFormatter. The method Deserialize() will take parameter of FileStream object which point to the binary file which you want to deserialize. You have to do explicit casting of Article type during Deserializing.

Create One Project For Serializing

Create one Articles.cs class file

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace BinarySerialization
{
    [Serializable()]
    public class Articles :ISerializable
    {
        public string sTitle;
        public string sAuthor;
        public string sText;
        public Articles()
        {}
        public Articles(SerializationInfo info,StreamingContext context)
        {
            sTitle =Convert.ToString(info.GetValue("Title",typeof(String)));
            sAuthor = Convert.ToString(info.GetValue("Author",typeof(String)));
            sText = Convert.ToString(info.GetValue("Text",typeof(String)));                   
        }
        public void serialize(string fileName)
        {
            FileStream s;
            s = new FileStream(fileName,FileMode.Create,FileAccess.ReadWrite);
            BinaryFormatter B = new BinaryFormatter();
            B.Serialize(s,this);
            s.Close();
        }
        public Articles deSerialize(string fileName)
        {
            FileStream Fs = new FileStream(fileName,FileMode.Open,FileAccess.Read);
            BinaryFormatter F = new BinaryFormatter();
            Articles s1 = (Articles)F.Deserialize(Fs);                       
            Fs.Close();
            return  s1;
        }
        #region ISerializable Members
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Title",sTitle);
            info.AddValue("Author",sAuthor);
            info.AddValue("Text",sText);
        }
        #endregion
    }
}

Create one webForm1.aspx page for testing the binary serialization.

//Binary Serialization of the object
Articles c1 = new Articles();
c1.sTitle = "My Title";
c1.sAuthor = "Author Name";
c1.sText ="This is my Text";
c1.serialize(@"C:\123.txt");

//deserialization of the object
Articles c2 = c1.deSerialize(@"C:\123.txt");
Response.Write(c2.sTitle);
Response.Write(c2.sAuthor);
Response.Write(c2.sText);


Recommended Free Ebook
Similar Articles