黑马程序员-数据二进制序列化

              

 

 要序列化 必须把需要序列化的类上声明:[Serializable]

 1 [Serializable]
 2     class Person
 3     {
 4         private string name;
 5 
 6         public string Name
 7         {
 8             get { return name; }
 9             set { name = value; }
10         }
11         private string path;
12 
13         public string Path
14         {
15             get { return path; }
16             set { path = value; }
17         }
18     }

 

序列化 数据

 1  string name = textBox1.Text;
 2             string path = textBox2.Text;
 3             Person p = new Person();
 4             p.Name = name;
          //保存文件路径
5 p.Path = path;
          //把数据加载到文件流中
6 using (FileStream fs = new FileStream("config", FileMode.Create)) 7 { 8 BinaryFormatter bf = new BinaryFormatter();
           //序列化数据
9 bf.Serialize(fs, p); 10 }

 

 

序列化 把正常的数据序列化 序列化之后的数据如下

 

 

 

反序列化  把序列化之后的数据反序列化出来

            Person p = new Person();
       //判断文件是否存在
if (File.Exists("config")) {
          //把文件读入文件流中
using (FileStream fs = new FileStream("config", FileMode.Open)) {
            //把数据加载到序列化中 BinaryFormatter bf
= new BinaryFormatter();
           //把数据反序列化出来 p
= bf.Deserialize(fs) as Person; listBox1.Items.Add(p.Name); } }

 

              

posted @ 2013-04-16 13:28  AlianBlank  阅读(158)  评论(0编辑  收藏  举报