How to remove a persistent cookies before Expiration time ?

Cookies are the small pieces of information that are stored in client system or browser memory and helped as client site state management for an web based application. Generally we can have two types of cookies  Persistent Cookies Non Persistent Cookies

Persistent Cookies : also known as  permanent cookies, which is stored in client hard-drive until it expires . persistent cookies should have set with expiration dates. Sometimes its stays  until the user deletes the cookie. Persistent cookies are used to collect identifying information about the user from that system.

Non Persistent Cookies : This can be called as Temporary Cookies. If there is no expires time  defined then the cookie is  stored in browser memory .

Therefore there is no difference between modifying persistent or non-persistent cookies.  Only difference between them are Persistent cookies should have an Expatriation time defined within it.

Let’s have a quick look how to make cookies as persistent

        //Creting a Cookie Object
        HttpCookie _userInfoCookies = new HttpCookie("UserInfo");

       //Setting values inside it
        _userInfoCookies["UserName"] = "Abhijit";
        _userInfoCookies["UserColor"] = "Red";
        _userInfoCookies["Expire"] = "5 Days";
        
        //Adding Expire Time of cookies
         _userInfoCookies.Expires = DateTime.Now.AddDays(5);
        
        //Adding cookies to current web response
        Response.Cookies.Add(_userInfoCookies);

Now once you have set with the Cookies expires time , it will be stored in hard drive until expires or user manually delete or clear all the cookies. If you want your cookies need to be expires before the expiration time that you have mentioned earlier, you just need to override the cookies information.

     HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
        //Adding Expire Time of cookies before existing cookies time
        _userInfoCookies.Expires = DateTime.Now.AddDays(-1);
        //Adding cookies to current web response
        Response.Cookies.Add(_userInfoCookies);

This will override the existing cookies information.

For more information on ASP.NET Cookies, please read http://www.codeproject.com/KB/aspnet/Beginners_Cookies.aspx





Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

2 Comments to “How to remove a persistent cookies before Expiration time ?”

Comments are closed.