二进制文件序列化
二进制序列化的目的:为了能把对象,以二进制的形式存入文件中.
二进制序列化的操作步骤:(1)将要序列化的对象标记为[Serializable]
(2)定义一个BinnaryFormatter类
(3)调用BinnaryFormatter类的Serialize方法
class Program { static void Main(string[] args) { List<Person> list = new List<Person>(); list.Add(new Person("翟群", 18, '女')); //将对象以二进制形式存入文件 FileStream f = new FileStream("D:\\序列化文件.txt", FileMode.Create, FileAccess.Write); using (f) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(f, list); } } } [Serializable]//将Person类定义为可序列化的 class Person { public Person(string name,int age,char gender) { this.name = name; this.age = age; this.gender = gender; } private string name; public string Name { set { name = value; } get { return name; } } private int age; public int Age { set { age = value; } get { return age; } } private char gender; public char Gender { set { gender = value; } get { return gender; } } public void SayHello() { Console.WriteLine("大家好,我是{0},今年{1}岁,我是{2}", name, age, gender); } }
2.反序列化
//反序列化 FileStream f1 = new FileStream("D:\\序列化文件.txt", FileMode.Open, FileAccess.Read); using (f1) { BinaryFormatter b1 = new BinaryFormatter(); List<Person> ps=(List<Person>) b1.Deserialize(f1); }
我叫小小菜,想要成为一棵大大包心菜.