1.对象序列化
Person p1 = new Person();
p1.Age = 22;
p1.Name = "齐达内";
//对象序列化
using (Stream st = File.OpenWrite(@"D:\22.xml"))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(st, p1);
Console.WriteLine("成功");
}
2.对象反序列化
using (Stream st = File.OpenRead(@"D:\22.xml"))
{
BinaryFormatter bf = new BinaryFormatter();
object ob =bf.Deserialize(st);//得到的是一个object的对象
Type t = ob.GetType();
XElement person = new XElement(t.Name);//获取Person
//遍历所有公有字段
PropertyInfo[] properinfo = t.GetProperties();
foreach (var p in properinfo)
{
XElement name = new XElement(p.Name);
name.Value = p.GetValue(ob, null).ToString();//字段值怎么取出来
person.Add(name);
}
string xml = person.ToString();
using (Stream st1 = File.OpenWrite(@"D:\person.xml"))
{
byte[] bytes=new byte[1024];
bytes = Encoding.UTF8.GetBytes(xml);
st1.Write(bytes, 0, bytes.Length);
}
}