private void cookieSerilizse()
{
//序列化
string str = "I'm a test data";
IFormatter fm = new BinaryFormatter();//实例化一个二进制序列化对象
MemoryStream ms=new MemoryStream();//实例如化一个内存流对象
fm.Serialize(ms, str);//进行序列化
ms.Seek(0, SeekOrigin.Begin);//指定当前流的位置
StreamReader sr = new StreamReader(ms);//实例化流的新实例
string st = sr.ReadToEnd();//将流中的数据全部读出并赋给字符串变量
sr.Close();
HttpCookie hc = new HttpCookie("trent");//创建COOKIE
hc.Value = Server.UrlEncode(st);//将数据编码后赋给COOKIE
hc.Expires = DateTime.Now.AddMinutes(5);//设置COOKIE的有效期
Response.Cookies.Add(hc);//将数据写入COOKIE
//反序列化
HttpCookie hr = Request.Cookies["trent"];
Response.Write("<h1>未反序列化:</h1>"+hr.Value+"<br>");
string stri = Server.UrlDecode(hr.Value.ToString());
byte[] bt = System.Text.Encoding.Default.GetBytes(stri);
Stream smn = new MemoryStream(bt);
IFormatter fmn = new BinaryFormatter();
string strn =(string) fmn.Deserialize(smn);
Response.Write("<h1>已反序列化:</h1>"+strn+"<b>");
}
|
请发表评论