ASP.NET将物件序列化成Binary储存至DB or File

文章出处:中国站长站 作者:F6 Team 发布时间:2008-07-21

最近有人在讨论这个问题..小弟很少玩这个东西..就到网路上找了一些资源..教大家如何将物件序列化成Binary Data..然后储存到资料库或档桉裡..
当然可以序列化..就一定可以反序列化了...其实序列化格式不一定要是Binary Data..也可以是XML or SOAP Data的...

首先准备一个DB,结构如下:

接下来就是代码了

以下为引用的内容:

asp.net(c#)

SerializingObjects.aspx

view plaincopy to clipboardprint?
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SerializingObjects.aspx.cs" Inherits="SerializingObjects" %> 
 
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
http://www.w3.org/1999/xhtml" > 
 
    Serializing Objects 
 
 
   

 
   
 
         
            资料库 
            档桉 
       
 
         
 
         
         
         
 
         
         
         
 
         
         
 
         
         
       
 
     
 
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SerializingObjects.aspx.cs" Inherits="SerializingObjects" %>

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

http://www.w3.org/1999/xhtml" >

    Serializing Objects


   


   

       
            资料库
            档桉
       

       

       
       
       

       
       
       

       
       

       
       
       

   

SerializingObjects.aspx.cs

view plaincopy to clipboardprint?
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; }  
    }  
 

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; }
    }

}

执行结果: