Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

How do we create,Read,Delete Cookies in Asp.net

Posted by ramanisandeep on July 3, 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);
                        Response.Cookies.Add(aCookie);
                    }
                    else
                    {
                        //Delete Cookie
                        HttpCookie aCookie = new HttpCookie("AdminInfo");                       
                        aCookie.Expires = DateTime.Now.AddDays(-1);
                        Response.Cookies.Add(aCookie);
                    }

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);
           }
       }

   }

 

Technorati Tags:

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>