using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Serializer
{
public partial class Form1 : Form
{
MemoryStream mS = new MemoryStream();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnXmlSerializer_Click(object sender, EventArgs e)
{
XmlSerializer xs = new XmlSerializer(typeof(Users));
//XML序列化
using (StreamWriter sw = new StreamWriter("xmlSample.xml"))
{
Users ur = new Users();
ur.age = 22;
ur.sex = '男';
ur.SetName("张三");
xs.Serialize(sw, ur);//将ur对象序列化,写入流当中。;
}
//XML反序列化
using (StreamReader sr = new StreamReader("xmlSample.xml"))
{
Users u = (Users)xs.Deserialize(sr);//读取流,并反序列化成ur对象
MessageBox.Show("姓名:" + u.name + "/n" + "年龄:" + u.age + "/n");
}
}
private void btnBinary_Click(object sender, EventArgs e)
{
//二进制格式序列化
//使用该方式序列化必须在对象类定义前加上 [Serializable]属性,否则会报出XX类型未序列化的错误提示!
BinaryFormatter bf = new BinaryFormatter();
using (FileStream sw = new FileStream("xmlSample.bin",FileMode.OpenOrCreate,FileAccess.Write))
{
Users ur = new Users();
ur.age = 22;
ur.sex = '男';
ur.SetName("张三");
bf.Serialize(sw, ur);//将ur对象序列化,写入流当中。;
}
//反序列化
using (FileStream sr = new FileStream("xmlSample.bin", FileMode.OpenOrCreate, FileAccess.Read))
{
Users u = (Users)bf.Deserialize(sr);//读取流,并反序列化成ur对象
MessageBox.Show("姓名:" + u.name + "/n" + "年龄:" + u.age + "/n");
}
}
private void btnSOAP_Click(object sender, EventArgs e)
{
//SOAP同BinaryFormatter;
}
}
[Serializable]
public class Users
{
public int age;
public char sex;
public string name;
public void SetName(string _name)
{
name = _name;
}
public string GetName()
{
return name;
}
}
}