继承BinaryFormatter()类
[Serializable]//允许这个对象序列化 public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }
序列化
BinaryFormatter binaryFormatter = new BinaryFormatter(); if (!File.Exists("person.bin"))//判断是否读取到这个文件 { Person person = new Person()//给对象赋值 { Id = 1, Name = "Test", Age = 23 }; //将对象序列化为二进制数据 using (FileStream stream = new FileStream("person.bin", FileMode.Create)) { binaryFormatter.Serialize(stream, person); } }
反序列化
//从文件反序列化 using (FileStream stream1 = new FileStream("person.bin", FileMode.Open)) { Person person1 = (Person)binaryFormatter.Deserialize(stream1); //var person1 = binaryFormatter.Deserialize(stream1); Console.WriteLine("111"); Console.WriteLine(person1); ListViewItem item = new ListViewItem(); item.SubItems[0].Text = person1.Id.ToString(); item.SubItems.Add(person1.Name); item.SubItems.Add(person1.Age.ToString()); listView1.Items.Add(item); }
往序列化文件里继续添加
private bool AddFormatter(List<Person> persons,Person person) { if (Check(persons, person.Name) == false) { return false; } persons.Add(person);//添加进集合里 using (FileStream stream = new FileStream("person.bin", FileMode.Create)) { binaryFormatter.Serialize(stream, list);//重置 } return true; }
本文来自博客园,作者:阿霖找BUG,转载请注明原文链接:https://www.cnblogs.com/lin-07/p/17633946.html