DataSet Serialization and Deserialization using Binary Format
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Runtime.Serialization.Formatters.Binary" %>
<%@ Import Namespace="System.Web.Configuration" %>
<script runat="server">
void Page_Load(object sender, System.EventArgs e)
{
DataSet categories = GetCategories();
string fileName = Server.MapPath("App_Data/Data.dat");
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
categories.RemotingFormat = SerializationFormat.Binary;
BinaryFormatter format = new BinaryFormatter();
format.Serialize(stream, categories);
stream.Flush();
}
Response.Write("File written successfully");
}
void btnReadFromFile_Click(object sender, EventArgs e)
{
string fileName = Server.MapPath("App_Data/Data.dat");
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
BinaryFormatter format = new BinaryFormatter();
DataSet categoriesFromFile = (DataSet) format.Deserialize(stream);
gridCategories.DataSource = categoriesFromFile.Tables[0].DefaultView;
gridCategories.DataBind();
}
}
DataSet GetCategories()
{
string connString = WebConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;
string sql = "Select * from Production.ProductSubcategory";
DataSet categories = new DataSet("Categories");
using (SqlConnection connection = new SqlConnection(connString))
{
SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
adapter.Fill(categories);
}
return categories;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>DataSet Serialization and Deserialization using Binary Format</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="Server"
ID="btnReadFromFile"
OnClick="btnReadFromFile_Click"
Text="Read the Data from file" />
<br />
<asp:GridView id="gridCategories"
runat="server"
AutoGenerateColumns="False"
CellPadding="4"
HeaderStyle-BackColor="blue"
HeaderStyle-ForeColor="White"
HeaderStyle-HorizontalAlign="Center"
HeaderStyle-Font-Bold="True">
<Columns>
<asp:BoundField HeaderText="Category ID" DataField="ProductSubcategoryID" />
<asp:BoundField HeaderText="Name" DataField="Name" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField HtmlEncode="false" DataFormatString="{0:d}" HeaderText="Last Modified Date" DataField="ModifiedDate" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Related examples in the same category