C#的序列化和反序列化
代码块
简单的序列化程序:
using System;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button_OK_Click(object sender, EventArgs e)
{
Person p = new Person();
p.Name = "sun";
p.Sex = this.server_ip_value.Text;
//使用XML序列化对象
string fileName = @"..\..\Person.xml";//文件名称与路径
Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
XmlSerializer xmlFormat = new XmlSerializer(typeof(Person));
xmlFormat.Serialize(fStream, p);
fStream.Position = 0;//重置流位置
fStream.Close();
}
}
[Serializable]
public class Person
{
public string Name;//姓名
public string Sex;//性别,是否是男
//public Person() { }//必须提供无参构造器,否则XmlSerializer将出错
//public Person()
//{
// this.Name = "rong";
// this.Sex = "man";
//}
public override string ToString()
{
return "姓名:" + this.Name + "\t性别:" + (this.Sex);
}
}
}
简单测试界面: