"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Thursday, May 6, 2010

Create, Read, Write,Delete Cookies on Asp.Net C# with Sample

 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.
How to create the cookies:

//for store the values in the cookies
Response.Cookies["MyName"].Value = "Arun";
//how much time cookies save on the user hard drive
Response.Cookies["MyName"].Expires = DateTime.Now.AddDays(10);
// now this cookies save 10 days on the user hard drive.after 10 days this cookies expires.
if  we do not add   Response.Cookies["MyName"].Expires = DateTime.Now.AddDays(10); and  we create the cookie in that case cookie will not  store on the user hard drive, then it will  stores on the browser, when we close the browser the cookie automatically Expires.
How to Read the cookie:


When we want to read the cookies then first we check the cookie whether  exit or not:

            string myName = string.Empty;
            HttpCookie cookie = Request.Cookies["MyName"];
            if (cookie == null)
            {
                Label1.Text = "Oops Honey Some Error Coming ";

            }
            else
            {
                // assign cookie value in the variable.
                myName = Request.Cookies["MyName"].Value;
                Label1.Text = myName.ToString();
            }



How to Delete the cookies:
First we check cookie exit or not:

    HttpCookie cookie = Request.Cookies["MyName"];
            if (cookie == null)
            {
                Label1.Text = "Oops Honey... Some Error Coming ";

            }
            else
            {
                Response.Cookies["MyName"].Expires = DateTime.Now.AddDays(-1);

            }

  And Dear, I created a demo, U can download it from  here

Have a nice day... 'N happy Coding :)

Erin Baker's Breakfast Cookies, Double Chocolate Chunk, 3-Ounce Individually Wrapped Cookies (Pack of 12)Famous Amos- Chocolate Chip Cookies, 36 Pouches

No comments: