20150316--序列化和反序列化

序列化:把对象转化成流,流转化成文件、二进制。

反序列化:把流转化为对象。

序列化需要引用流、序列化两个类,

using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
还需要创建一个类(对象),

stuDA类(封装了3个变量code、name、nation):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

[Serializable]//标记为可序列化
/// <summary>
/// stuDA 的摘要说明
/// </summary>
public class stuDA
{
    public stuDA()
    {
    }
    private string code;

    public string Code
    {
        get { return code; }
        set { code = value; }
    }
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    private string nation;

    public string Nation
    {
        get { return nation; }
        set { nation = value; }
    }
}

注意:以上代码中加粗部分,[Serializable]重要语句,将这个类标记为可序列化,否则将会报错。

新建页面,并添加控件:

image

序列化按钮代码:

//序列化按钮
    protected void Button1_Click(object sender, EventArgs e)
    {
        stuDA ss = new stuDA
        {
            Code = TextBox1.Text,
            Name = TextBox2.Text,
            Nation = TextBox3.Text
        };
        FileStream fs = null;
        try
        {
            string path = Server.MapPath("data/aaa.txt");//映射服务器端的硬盘物理路径
            fs = new FileStream(path, FileMode.Create);//建立文件流
            BinaryFormatter bf = new BinaryFormatter();//二进制转换器
            bf.Serialize(fs, ss);//把对象序列化为给定流
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();//流使用后必须关闭。
            }
        }
    }

反序列化按钮代码:

//反序列化按钮
    protected void Button2_Click(object sender, EventArgs e)
    {
        string path = Server.MapPath("data/aaa.txt");
        FileStream fs = null;
        try
        {
            fs = new FileStream(path, FileMode.Open);//使用流打开文件

            BinaryFormatter by = new BinaryFormatter();//二级制转化器

            stuDA sdata = (stuDA)by.Deserialize(fs);//反序列化成对象
            Label1.Text = sdata.Code;
            Label2.Text = sdata.Name;
            Label3.Text = sdata.Nation;

        }
        finally
        {
            if(fs!=null)
            {
                fs.Close();
            }
        }
    }

在三个文本框中分别输入字母或汉字,点击序列化:

image

注意:文件将会生成在该网站的目录下 data文件中,data文件需要预先创建。

image

打开文件可以看到一些略有规律的乱码(因为使用二进制的关系):

image

清空文本框的内容,点击反序列化:

image

原文地址:https://www.cnblogs.com/Tirisfal/p/4342289.html