序列化之一 BinaryFormatter

 

有时候用户进行了某些操作,想要一直保留这个记录或者说服务器为了保存用户的信息或者状态可以用BinaryFormatter

 

//=====以流的形式将对象进行序列化========

        /// <summary>
        /// 序列化
        /// </summary>
        static void Serialize()
        {
            List<string> strValue = new List<string>();
            strValue.Add("哈哈");
            strValue.Add("嘿嘿");
            strValue.Add("呵呵");
            strValue.Add("嘎嘎");
            BinaryFormatter bf = new BinaryFormatter();
            using (Stream stream = File.OpenWrite(@"H:\binary.xxx"))
            {
                bf.Serialize(stream, strValue);
            }
        }

 

// ==========将流反序列化成对象============

        /// <summary>
        /// 将流反序列化成对象
        /// </summary>
        static void Deserialize()
        {          
                BinaryFormatter bf = new BinaryFormatter();
                if (!File.Exists(@"H:\binary.xxx"))
                {
                    throw new Exception("找不到对象存储位置");
                }
                using (Stream stream = File.OpenRead(@"H:\binary.xxx"))
                {
                    object obj = bf.Deserialize(stream);
                    List<string> listVlaue = (List<string>)(obj);
                    foreach (string str in listVlaue)
                    {
                        Console.WriteLine(str);
                    }
                }           
        }

 

这样只要进行一次序列化就会把序列化的信息以流的形式存储到指定的位置,下次用可以直接取。用BinaryFormatter还可以序列化复杂的对象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章