Deleting a cookie—physically removing it from the user’s hard disk—is a trick on modifying it. You cannot directly remove a cookie because the cookie is on the user’s computer. However, you can have the browser delete the cookie for you. The technique is to create a new cookie with the same name as the cookie to be deleted, but to set the cookie’s expiration to a date earlier than today. When the browser checks the cookie’s expiration, the browser will discard the now-outdated cookie. The following code example shows one way to delete all the cookies available to the application:

Visual Basic

Dim aCookie As HttpCookie
Dim i As Integer
Dim cookieName As String
Dim limit As Integer = Request.Cookies.Count – 1
For i = 0 To limit
cookieName = Request.Cookies(i).Name
aCookie = New HttpCookie(cookieName)
aCookie.Expires = DateTime.Now.AddDays(-1)
Response.Cookies.Add(aCookie)
Next

C#

HttpCookie aCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i
{
cookieName = Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(aCookie);
}

Leave a Reply