标签:
1 using (FileStream fsWrite=new FileStream(string path,FileMode,FileAccess.Read) 2 BinaryFormatter bf=new BinaryFormatter(); 3 void bf.Serialize(Stream ,Object);//自动执行了fsWrite.Write();
[Serializable]//标记可序列化 public class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } } class Program { public static void Main(string[] args) { Person p=new Person(); p.Name="666"; using(FileStream fsWrite=new FileStream(@"D:\123.txt",FileMode.OpenOrCreate,FileAccess.Write)) { BinaryFormatter bf=new BinaryFormatter();//创建序列化器 bf.Serialize(fsWrite,p);//序列化 } using ( FileStream fsRead=new FileStream(@"D:\123.txt",FileMode.Open,FileAccess.Read) ){ Person pp; BinaryFormatter bb=new BinaryFormatter(); pp=(Person)bb.Deserialize(fsRead);//这里返回objec,反序列化 Console.WriteLine(pp.Name); Console.ReadKey(); } } }
1 List<Person> list = new List<Person>(); 2 list.Add(new Person() { Name = "AAAA", Age = 19, Email = "ysh@yahoo.com" }); 3 list.Add(new Person() { Name = "BBBB", Age = 29, Email = "swb@yahoo.com" }); 4 list.Add(new Person() { Name = "BBBB", Age = 16, Email = "ylp@yahoo.com" }); 5 6 //使用JavaScript 序列化。 7 JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); 8 string str = jsSerializer.Serialize(list); 9 //jsSerializer.Deserialize();//反序列化 10 File.WriteAllText("list.txt", str); 11 Console.WriteLine(str); 12 Console.ReadKey();
1 List<Person> list = new List<Person>(); 2 list.Add(new Person() { Name = "AAAA", Age = 19, Email = "ysh@yahoo.com" }); 3 list.Add(new Person() { Name = "BBBB", Age = 29, Email = "swb@yahoo.com" }); 4 list.Add(new Person() { Name = "CCCC", Age = 16, Email = "ylp@yahoo.com" }); 5 //xml序列化 6 //XmlSerializer xmlSerializer = new XmlSerializer(list.GetType()); 7 XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Person>)); 8 using (FileStream fsWrite = File.OpenWrite("list.xml")) 9 { 10 xmlSerializer.Serialize(fsWrite, list); 11 //xmlSerializer.Deserialize();//反序列化 12 } 13 Console.WriteLine("ok"); 14 Console.ReadKey();
标签:
原文地址:http://www.cnblogs.com/Recoding/p/4457129.html