码迷,mamicode.com
首页 > 其他好文 > 详细

序列化

时间:2015-03-20 09:13:07      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

序列化:对象--->流--->文件、二进制
using System.Runtime.Serialization.Formatters.Binary;//二进制序列化器所在命名空间
using System.Runtime.Serialization.Formatters.Soap;//
using System.IO;//流的

反序列化:流--->对象

一个类要想能够序列化,需要给这个类加一个attribute:即在类的定义之前加[Serializable]

二进制格式化器进行序列化:
StudentData data = new StudentData
{
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,data);//序列化方法
}
finally
{
if (fs != null)
{
fs.Close();
}
}
反序列化:
string path = Server.MapPath("data/aaa.txt");
FileStream fs = null;
try
{
fs = new FileStream(path,FileMode.Open);//使用流打开文件

BinaryFormatter bf = new BinaryFormatter();//造一个二进制格式化器
//反序列化
StudentData sdata = (StudentData)bf.Deserialize(fs);
TextBox1.Text = sdata.Code;
TextBox2.Text = sdata.Name;
TextBox3.Text = sdata.Nation;

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

Soap序列化:
StudentData data = new StudentData
{
Code = TextBox1.Text,
Name = TextBox2.Text,
Nation = TextBox3.Text
};//造对象
FileStream fs = null;
try
{
string path = Server.MapPath("data/bbb.txt");//映射物理路径
fs = new FileStream(path, FileMode.Create);//建好了文件流
SoapFormatter sf = new SoapFormatter();//soap格式化器
sf.Serialize(fs,data);//序列化
}
finally
{
if (fs != null)
{
fs.Close();
}
}
soap反序列化:
string path = Server.MapPath("data/bbb.txt");
FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Open);//使用流打开文件

SoapFormatter bf = new SoapFormatter();//造一个二进制格式化器
//反序列化
StudentData sdata = (StudentData)bf.Deserialize(fs);
TextBox1.Text = sdata.Code;
TextBox2.Text = sdata.Name;
TextBox3.Text = sdata.Nation;

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

网站发布:
1.要装iis
2.要装程序需要的环境:framework框架
3.将iis指定到程序文件

序列化

标签:

原文地址:http://www.cnblogs.com/mxx0426/p/4352766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!