Google News
logo
ADO.NET - Interview Questions
What is serialization? Write an example program to serialize a DataSet.
Serialization is the method of converting an object into a byte stream which can be stored as well as transmitted over the network. The advantage of serialization is that data can be transmitted in a cross-platform environment across the network and also it can be saved in a storage medium like persistent or non-persistent.
 
The code for serializing a DataSet is :
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml.Serialization;
using System.IO;
public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection("Data Source=data_source_name;Initial Catalog=employee;Integrated Security=True");  //Create connection object
        SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);  //DataAdapter creation
        DataSet s = new DataSet();
        da.Fill(s);  
        FileStream fObj = new FileStream("C:\\demo.xml", FileMode.Create);   // Create a XML file
        XmlSerializer sObj = new XmlSerializer(typeof(DataSet));
        sObj.Serialize(fObj, s);  //Serialization of a DataSet
        fObj.Close();
    }
}
In the above given example, the database name is employee and, the table name is emp. The data in a DataSet will be serialized and stored in a demo.xml file by using Serialize() method.
Advertisement