序列化类:
[Serializable()]
public class SerializableObject
{
public int Index { get; set; }
public string Name { get; set; }
}
序列化/反序列化方法:
SerializableObject obj = new SerializableObject { Index = 1, Name = "属性1" };
// 一, XML 序列化和反序列化
XmlSerializer xmlSerializer = new XmlSerializer(typeof(SerializableObject));
using (MemoryStream ms = new MemoryStream())
{
// 1, XML 序列化
xmlSerializer.Serialize(ms, obj);
// 以字符串形式显示序列化结果
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
string xmlString = sr.ReadToEnd();
// 2, XML 反序列化
ms.Seek(0, SeekOrigin.Begin);
SerializableObject newObj = (SerializableObject)xmlSerializer.Deserialize(ms);
sr.Close();
}
// 二, 二进制序列化和反序列化
BinaryFormatter binSerializer = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
// 1, 二进制序列化
binSerializer.Serialize(ms, obj);
// 以字符串形式显示序列化结果
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
string xmlString = sr.ReadToEnd();
// 2, 二进制反序列化
ms.Seek(0, SeekOrigin.Begin);
SerializableObject newObj = (SerializableObject)binSerializer.Deserialize(ms);
sr.Close();
}
XML序列化可以看看这篇文章:http://www.cnblogs.com/baby_shark/archive/2008/12/25/1362358.html
二进制可以看这篇:http://www.cnblogs.com/suneryong/archive/2007/06/13/781818.html
还有篇你可以参考下,包含了XML序列化和2进制的:
http://www.cnblogs.com/baby_shark/archive/2008/12/25/1362358.html