Search Asp.Net Here

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());
Try it


Comments :

2 comments to “How to Create and Read cookies in Asp.Net and C#.Net”
Anonymous said...
on 

I want to read exist file cookie of other project. please, help me?

Pranav Singh said...
on 

This is really nice article related to cookies. have a look of this article also
http://aspdotnetpools.blogspot.in/2013/08/how-to-create-cookies-in-aspnet.html

Post a Comment