Fly
Believe Me I Can Fly , I Am Singing In The Sky

二进制序列化:

  序列化就是将对象从内存中移到硬盘(使用FileStream)或者向网络(使用NetWorkStream)中传送。可认为是格式化数据。

  1 使用时先添加命名空间:

      using System.Runtime.Serialization.Formatters.Binary;

  2  BinaryFormatter bf = new BinaryFormatter();   实例化

  3 使用  [Serializable] 标记,将它添加到要序列化的对象上;

   例1:

 [Serializable]
    class Person
    {
        public int Num;
        public string Name;
    }

 static void Main(string[] args)
        {
            string path = @"D:\txt";  //找一个能够写入的路径,
            List<Person> personList = new  List<Person>(); //将Person类写成集合;
            Person ps = new Person();
            ps.Num = 10;
            ps.Name = "往";
            personList.Add(ps);
            //创建一个写入的文件流,  Path.Combine();将路径和文件名拼接

    //要添加命名空间  using System.IO;
            FileStream writer=new FileStream(Path.Combine(path,"ps.txt"),FileMode.Open,FileAccess.Write);
            using (writer)
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(writer, personList);
            }
            //序列化完成,那么怎样能读出?
            //反序列化
            FileStream Reader = new FileStream(Path.Combine(path, "ps.txt"), FileMode.Open, FileAccess.Read);
            using (Reader)
            {
                BinaryFormatter bf1 = new BinaryFormatter();
              
              personList = (List<Person>)bf1.Deserialize(Reader);
            }

    Console.ReadKey();

}

    例2:

    string path = @"D:\txt\ps.txt"; 

    List<int> lis = new List<int>() {1,2,3,4,5,6 };
            ////把对象二进制序列化;
            BinaryFormatter bf = new BinaryFormatter(); //序列化器
            FileStream file = new FileStream(path, FileMode.Open, FileAccess.Write);
            using(file)
            {
                bf.Serialize(file,lis);
            }

            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
            using (file)
            {
                List<int> lis=(List<int>)bf.Deserialize(file);
                for (int i = 0; i < lis.Count; i++)
                {
                    Console.WriteLine(lis[i]);
                }
            }
            Console.ReadKey();

 

    

posted on 2012-07-03 23:06  梁彦伟  阅读(342)  评论(0)    收藏  举报