1.二进制序列化器
/// <summary> /// 二进制序列化器 /// </summary> public static void BinarySerialize() { //使用二进制序列化对象 string fileName = Path.Combine(Constant.SerializeDataPath, @"BinarySerialize.txt");//文件名称与路径 using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) {//需要一个stream,这里是直接写入文件了 List<Programmer> pList = DataFactory.BuildProgrammerList(); BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器 binFormat.Serialize(fStream, pList); } using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite)) {//需要一个stream,这里是来源于文件 BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器 //使用二进制反序列化对象 fStream.Position = 0;//重置流位置 List<Programmer> pList = (List<Programmer>)binFormat.Deserialize(fStream);//反序列化对象 } }
2.Soap序列化器
public static void SoapSerialize() { //使用Soap序列化对象 string fileName = Path.Combine(Constant.SerializeDataPath, @"SoapSerialize.txt");//文件名称与路径 using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) { List<Programmer> pList = DataFactory.BuildProgrammerList(); SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器 //soapFormat.Serialize(fStream, list);//SOAP不能序列化泛型对象 soapFormat.Serialize(fStream, pList.ToArray()); } using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite)) { SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器 //使用二进制反序列化对象 fStream.Position = 0;//重置流位置 List<Programmer> pList = ((Programmer[])soapFormat.Deserialize(fStream)).ToList();//反序列化对象 } }
3.xml序列化器
public static void XmlSerialize() { //使用XML序列化对象 string fileName = Path.Combine(Constant.SerializeDataPath, @"Student.xml");//文件名称与路径 using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) { List<Programmer> pList = DataFactory.BuildProgrammerList(); XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//创建XML序列化器,需要指定对象的类型 xmlFormat.Serialize(fStream, pList); } using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite)) { XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//创建XML序列化器,需要指定对象的类型 //使用XML反序列化对象 fStream.Position = 0;//重置流位置 List<Programmer> pList = pList = (List<Programmer>)xmlFormat.Deserialize(fStream); } }
4.json序列化器