Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

How to create,Read,Delete Cookies in

Posted by Viral Sarvaiya on September 10, 2009

A cookie is a small bit of text file that browser creates and stores on your machine (hard drive). Cookie is a small piece of information stored as a string. Web server sends the cookie and browser stores it, next time server returns that cookie.Cookies are mostly used to store the information about the user. Cookies are stores on the client side.

Here i m going to explain you by providing example of Remember me Code :

Step 1 : if check box is checked for “Remember Me” then create cookie else Delete it.

if (chkRememberMe.Checked == true)
//Create Cookie to Store AdminInfo
HttpCookie aCookie = new HttpCookie("AdminInfo");
aCookie.Values["userName"] = txtUsername.Text;
aCookie.Values["Password"] = txtPassword.Text;
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(10);
//Delete Cookie
HttpCookie aCookie = new HttpCookie("AdminInfo");
aCookie.Expires = DateTime.Now.AddDays(-1);

Step 2 : now check cookie is null or not in page load event & set username & password from cookie

protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
if (Request.Cookies["AdminInfo"] != null)
txtUsername.Text = Request.Cookies["AdminInfo"]["userName"] == null ? null : Request.Cookies["AdminInfo"]["userName"].ToString();
string pwd = Request.Cookies["AdminInfo"]["Password"] == null ? null : Request.Cookies["AdminInfo"]["Password"].ToString();
txtPassword.Attributes.Add("value", pwd);


2 Responses to “How to create,Read,Delete Cookies in”

  1. Developer said

    Few things to note:
    1. Storing password is not safe!
    2. Reading cookie from client side and setting back to a textbox as shown above will have XSS vulnerability

  2. […] have already writen that how to use cookies in and silverlight from below post and […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: