最近有人在討論這個問題..小弟很少玩這個東西..就到網路上找了一些資源..
教大家如何將物件序列化成Binary Data..然後儲存到資料庫或檔案裡..
當然可以序列化..就一定可以反序列化了...
其實序列化格式不一定要是Binary Data..也可以是XML or SOAP Data的...
首先準備一個DB,結構如下:
接下來就是程式碼了
asp.net(c#)
SerializingObjects.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="SerializingObjects.aspx.cs" Inherits="SerializingObjects" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>Serializing Objects</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:DropDownList ID="ddlType" runat="server">
- <asp:ListItem Value="0">資料庫</asp:ListItem>
- <asp:ListItem Value="1">檔案</asp:ListItem>
- </asp:DropDownList>
- <asp:Button ID="btnLoad" runat="server" OnClick="btnLoad_Click" Text="讀取" />
- <asp:Label ID="Label1" runat="server" Text="編號:"></asp:Label>
- <asp:TextBox ID="txbId" runat="server"></asp:TextBox>
- <asp:Label ID="Label2" runat="server" Text="名稱:"></asp:Label>
- <asp:TextBox ID="txbName" runat="server"></asp:TextBox>
- <asp:Label ID="Label3" runat="server" Text="電話:"></asp:Label>
- <asp:TextBox ID="txbTel" runat="server"></asp:TextBox>
- <asp:Label ID="Label4" runat="server" Text="地址:"></asp:Label>
- <asp:TextBox ID="txbAddress" runat="server"></asp:TextBox>
- <asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="新增" /></div>
- </form>
- </body>
- </html>
SerializingObjects.aspx.cs
- using System;
- using System.Data;
- using System.Configuration;
- using System.Collections;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- using System.Data.SqlClient;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- public partial class SerializingObjects : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void btnAdd_Click(object sender, EventArgs e)
- {
- if (this.ddlType.SelectedIndex == 0)
- {
- SaveToDB();
- }
- else
- {
- SaveToFile();
- }
- }
- //存至資料庫(Binary Serialization)
- protected void SaveToDB()
- {
- using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
- {
- using (MemoryStream ms = new MemoryStream())
- {
- conn.Open();
- Member mem = new Member();
- mem.Id = this.txbId.Text;
- mem.Name = this.txbName.Text;
- mem.Tel = this.txbTel.Text;
- mem.Address = this.txbAddress.Text;
- BinaryFormatter b = new BinaryFormatter();
- b.Serialize(ms, mem);
- ms.Seek(0, 0);
- string sql = "insert into member values(@data)";
- SqlCommand cmd = new SqlCommand(sql, conn);
- cmd.Parameters.Add("@data", SqlDbType.Binary).Value = ms.ToArray();
- cmd.ExecuteNonQuery();
- }
- }
- }
- //由資料庫讀取(Binary Serialization)
- protected void LoadFromDB()
- {
- using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
- {
- using (MemoryStream ms = new MemoryStream())
- {
- conn.Open();
- string sql = "select data from member";
- SqlCommand cmd = new SqlCommand(sql, conn);
- SqlDataAdapter adapter = new SqlDataAdapter(cmd);
- DataTable dt = new DataTable();
- adapter.Fill(dt);
- if (dt.Rows.Count > 0)
- {
- byte[] buffer = (byte[])dt.Rows[dt.Rows.Count-1][0];
- ms.Write(buffer, 0, buffer.Length);
- ms.Seek(0, 0);
- BinaryFormatter b = new BinaryFormatter();
- Member mem = new Member();
- mem = (Member)b.Deserialize(ms);
- this.txbId.Text = mem.Id;
- this.txbName.Text = mem.Name;
- this.txbTel.Text = mem.Tel;
- this.txbAddress.Text = mem.Address;
- }
- }
- }
- }
- //存至檔案(Binary Serialization)
- protected void SaveToFile()
- {
- string path = Server.MapPath("member.dat");
- using (Stream s = File.Open(path, FileMode.Create))
- {
- Member mem = new Member();
- mem.Id = this.txbId.Text;
- mem.Name = this.txbName.Text;
- mem.Tel = this.txbTel.Text;
- mem.Address = this.txbAddress.Text;
- BinaryFormatter b = new BinaryFormatter();
- b.Serialize(s, mem);
- }
- }
- //由檔案讀取(Binary Serialization)
- protected void LoadFromFile()
- {
- string path = Server.MapPath("member.dat");
- if (File.Exists(path))
- {
- using (Stream s = File.Open(path, FileMode.Open))
- {
- BinaryFormatter b = new BinaryFormatter();
- Member mem = new Member();
- mem = (Member)b.Deserialize(s);
- this.txbId.Text = mem.Id;
- this.txbName.Text = mem.Name;
- this.txbTel.Text = mem.Tel;
- this.txbAddress.Text = mem.Address;
- }
- }
- }
- protected void btnLoad_Click(object sender, EventArgs e)
- {
- if (this.ddlType.SelectedIndex == 0)
- {
- LoadFromDB();
- }
- else
- {
- LoadFromFile();
- }
- }
- }
- [Serializable]
- public class Member
- {
- private string _id = string.Empty;
- private string _name = string.Empty;
- private string _tel = string.Empty;
- private string _address = string.Empty;
- public Member()
- {
- }
- public Member(string id, string name,string tel,string address)
- {
- _id = id;
- _name = name;
- _tel = tel;
- _address = address;
- }
- public string Id
- {
- get { return _id; }
- set { _id = value; }
- }
- public string Name
- {
- get { return _name; }
- set { _name = value; }
- }
- public string Tel
- {
- get { return _tel; }
- set { _tel = value; }
- }
- public string Address
- {
- get { return _address; }
- set { _address = value; }
- }
- }
執行結果: