序列化對象

 public static  void setUserStat(Model.UserStat model)
       {
           HttpCookie cookie = new HttpCookie("bloghu");
           cookie.Expires = DateTime.Now.AddHours(1);
           cookie.Value = Serialize(model);
           System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
       }
       public static Model.UserStat getCurrentUserStat()
       {
           if (System.Web.HttpContext.Current.Request.Cookies["bloghu"] != null)
               return (Model.UserStat)Deserialize(System.Web.HttpContext.Current.Request.Cookies["bloghu"].Value);
           else
               return new Model.UserStat();
       }
      static string Serialize(object obj)
       {
           MemoryStream stream = new MemoryStream();
           BinaryFormatter formatter = new BinaryFormatter();
           formatter.Serialize(stream, obj);
           return Convert.ToBase64String(stream.ToArray());
       }
       static object Deserialize(string str)
       {
           BinaryFormatter formatter = new BinaryFormatter();
           MemoryStream stream = new MemoryStream(Convert.FromBase64String(str));
           return formatter.Deserialize(stream);
       }
 
發佈了29 篇原創文章 · 獲贊 3 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章