Monday, September 12, 2011

How To Create And Read Cookies In Asp.Net And C#.Net

Cookies store user information in a text file and stored on user hard drive.here are some exmaples of how we can create cookies and read from them.

Creating Induvisual cookies
Indivisulal cookies are cookies which can store only single value
First way to create cookie Indivisulal (using Response object)
Response.Cookies["un"].Value = TextBox1.Text;
Response.Cookies["un"].Expires = DateTime.Now.AddMinutes(10);

Second way to create cookie Indivisulal (using HttpCookie Class)

HttpCookie ck = new HttpCookie("un1", TextBox1.Text);
ck.Expires = DateTime.Now.AddMinutes(10);Response.Cookies.Add(ck);

Reading from indivisual cookies

Response.Write(Request.Cookies["un"].Value);
//or
HttpCookie d = Request.Cookies["un1"].Value;Response.Write(d.Value);
Creating Sub-Key cookies
//First Method
Response.Cookies["myckk"]["un"] = TextBox1.Text;
Response.Cookies["myckk"]["up"] = TextBox2.Text;
Response.Cookies["myckk'"].Expires = DateTime.Now.AddMinutes(10);
//Second method
HttpCookie ck = new HttpCookie("myckk");
ck.Values.Add("un", TextBox1.Text);
ck.Values.Add("up", TextBox2.Text);
ck.Expires = DateTime.Now.AddMinutes(10);
Response.Cookies.Add(ck);
Response.Redirect("Default2.aspx");
Reading Sub-Key cookies
//First Mehtod ( with Request object)
Response.Write(Request.Cookies["myckk"]["un"].ToString());
Response.Write(Request.Cookies["myckk"]["up"].ToString());
Response.Redirect("Default2.aspx");

//Second Method
HttpCookie ck = Request.Cookies["myckk"];
Response.Write(ck.Values["un"].ToString());
Response.Write(ck.Values["un"].ToString());


No comments :

Post a Comment