ASP.NET將物件(Object)序列化(Serialize)成Binary儲存至DB or File

最近有人在討論這個問題..小弟很少玩這個東西..就到網路上找了一些資源..
教大家如何將物件序列化成Binary Data..然後儲存到資料庫或檔案裡..
當然可以序列化..就一定可以反序列化了...
其實序列化格式不一定要是Binary Data..也可以是XML or SOAP Data的...

 首先準備一個DB,結構如下:

接下來就是程式碼了

asp.net(c#)

SerializingObjects.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="SerializingObjects.aspx.cs" Inherits="SerializingObjects" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml" >  
  6. <head runat="server">  
  7.     <title>Serializing Objects</title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <asp:DropDownList ID="ddlType" runat="server">  
  13.             <asp:ListItem Value="0">資料庫</asp:ListItem>  
  14.             <asp:ListItem Value="1">檔案</asp:ListItem>  
  15.         </asp:DropDownList>  
  16.         <asp:Button ID="btnLoad" runat="server" OnClick="btnLoad_Click" Text="讀取" />  
  17.   
  18.         <asp:Label ID="Label1" runat="server" Text="編號:"></asp:Label>  
  19.         <asp:TextBox ID="txbId" runat="server"></asp:TextBox>  
  20.           
  21.   
  22.         <asp:Label ID="Label2" runat="server" Text="名稱:"></asp:Label>  
  23.         <asp:TextBox ID="txbName" runat="server"></asp:TextBox>  
  24.           
  25.   
  26.         <asp:Label ID="Label3" runat="server" Text="電話:"></asp:Label>  
  27.         <asp:TextBox ID="txbTel" runat="server"></asp:TextBox>  
  28.   
  29.         <asp:Label ID="Label4" runat="server" Text="地址:"></asp:Label>  
  30.         <asp:TextBox ID="txbAddress" runat="server"></asp:TextBox>  
  31.         <asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="新增" /></div>  
  32.     </form>  
  33. </body>  
  34. </html>  

SerializingObjects.aspx.cs

  1. using System;   
  2. using System.Data;   
  3. using System.Configuration;   
  4. using System.Collections;   
  5. using System.Web;   
  6. using System.Web.Security;   
  7. using System.Web.UI;   
  8. using System.Web.UI.WebControls;   
  9. using System.Web.UI.WebControls.WebParts;   
  10. using System.Web.UI.HtmlControls;   
  11. using System.Data.SqlClient;   
  12. using System.IO;   
  13. using System.Runtime.Serialization.Formatters.Binary;   
  14.   
  15. public partial class SerializingObjects : System.Web.UI.Page   
  16. {   
  17.     protected void Page_Load(object sender, EventArgs e)   
  18.     {   
  19.   
  20.     }   
  21.     protected void btnAdd_Click(object sender, EventArgs e)   
  22.     {   
  23.         if (this.ddlType.SelectedIndex == 0)   
  24.         {   
  25.             SaveToDB();   
  26.         }   
  27.         else  
  28.         {   
  29.             SaveToFile();   
  30.         }   
  31.     }   
  32.   
  33.     //存至資料庫(Binary Serialization)   
  34.     protected void SaveToDB()   
  35.     {   
  36.         using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))   
  37.         {   
  38.             using (MemoryStream ms = new MemoryStream())   
  39.             {   
  40.                 conn.Open();   
  41.   
  42.                 Member mem = new Member();   
  43.                 mem.Id = this.txbId.Text;   
  44.                 mem.Name = this.txbName.Text;   
  45.                 mem.Tel = this.txbTel.Text;   
  46.                 mem.Address = this.txbAddress.Text;   
  47.   
  48.                 BinaryFormatter b = new BinaryFormatter();   
  49.                 b.Serialize(ms, mem);   
  50.                 ms.Seek(0, 0);   
  51.   
  52.                 string sql = "insert into member values(@data)";   
  53.                 SqlCommand cmd = new SqlCommand(sql, conn);   
  54.                 cmd.Parameters.Add("@data", SqlDbType.Binary).Value = ms.ToArray();   
  55.                 cmd.ExecuteNonQuery();   
  56.   
  57.             }   
  58.         }   
  59.     }   
  60.   
  61.     //由資料庫讀取(Binary Serialization)   
  62.     protected void LoadFromDB()   
  63.     {   
  64.         using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))   
  65.         {   
  66.             using (MemoryStream ms = new MemoryStream())   
  67.             {   
  68.                 conn.Open();   
  69.   
  70.                 string sql = "select data from member";   
  71.                 SqlCommand cmd = new SqlCommand(sql, conn);   
  72.                 SqlDataAdapter adapter = new SqlDataAdapter(cmd);   
  73.                 DataTable dt = new DataTable();   
  74.                 adapter.Fill(dt);   
  75.   
  76.                 if (dt.Rows.Count > 0)   
  77.                 {   
  78.                     byte[] buffer = (byte[])dt.Rows[dt.Rows.Count-1][0];   
  79.                     ms.Write(buffer, 0, buffer.Length);   
  80.                     ms.Seek(0, 0);   
  81.                     BinaryFormatter b = new BinaryFormatter();   
  82.                     Member mem = new Member();   
  83.                     mem = (Member)b.Deserialize(ms);   
  84.   
  85.                     this.txbId.Text = mem.Id;   
  86.                     this.txbName.Text = mem.Name;   
  87.                     this.txbTel.Text = mem.Tel;   
  88.                     this.txbAddress.Text = mem.Address;   
  89.                 }   
  90.             }   
  91.         }   
  92.     }   
  93.   
  94.     //存至檔案(Binary Serialization)   
  95.     protected void SaveToFile()   
  96.     {   
  97.         string path = Server.MapPath("member.dat");   
  98.         using (Stream s = File.Open(path, FileMode.Create))   
  99.         {   
  100.             Member mem = new Member();   
  101.             mem.Id = this.txbId.Text;   
  102.             mem.Name = this.txbName.Text;   
  103.             mem.Tel = this.txbTel.Text;   
  104.             mem.Address = this.txbAddress.Text;   
  105.   
  106.             BinaryFormatter b = new BinaryFormatter();   
  107.             b.Serialize(s, mem);   
  108.         }   
  109.     }   
  110.   
  111.     //由檔案讀取(Binary Serialization)   
  112.     protected void LoadFromFile()   
  113.     {   
  114.         string path = Server.MapPath("member.dat");   
  115.         if (File.Exists(path))   
  116.         {   
  117.             using (Stream s = File.Open(path, FileMode.Open))   
  118.             {   
  119.                 BinaryFormatter b = new BinaryFormatter();   
  120.                 Member mem = new Member();   
  121.                 mem = (Member)b.Deserialize(s);   
  122.   
  123.                 this.txbId.Text = mem.Id;   
  124.                 this.txbName.Text = mem.Name;   
  125.                 this.txbTel.Text = mem.Tel;   
  126.                 this.txbAddress.Text = mem.Address;   
  127.             }   
  128.         }   
  129.     }   
  130.   
  131.     protected void btnLoad_Click(object sender, EventArgs e)   
  132.     {   
  133.         if (this.ddlType.SelectedIndex == 0)   
  134.         {   
  135.             LoadFromDB();   
  136.         }   
  137.         else  
  138.         {   
  139.             LoadFromFile();   
  140.         }   
  141.     }   
  142. }   
  143.   
  144.   
  145. [Serializable]   
  146. public class Member   
  147. {   
  148.     private string _id = string.Empty;   
  149.     private string _name = string.Empty;   
  150.     private string _tel = string.Empty;   
  151.     private string _address = string.Empty;   
  152.   
  153.     public Member()   
  154.     {   
  155.   
  156.     }   
  157.   
  158.     public Member(string id, string name,string tel,string address)   
  159.     {   
  160.         _id = id;   
  161.         _name = name;   
  162.         _tel = tel;   
  163.         _address = address;   
  164.     }   
  165.   
  166.     public string Id   
  167.     {   
  168.         get { return _id; }   
  169.         set { _id = value; }   
  170.     }   
  171.   
  172.     public string Name   
  173.     {   
  174.         get { return _name; }   
  175.         set { _name = value; }   
  176.     }   
  177.   
  178.     public string Tel   
  179.     {   
  180.         get { return _tel; }   
  181.         set { _tel = value; }   
  182.     }   
  183.   
  184.     public string Address   
  185.     {   
  186.         get { return _address; }   
  187.         set { _address = value; }   
  188.     }   
  189.   
  190. }  

執行結果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值