Asp.Net : Read,Write and Delete Cookies

What is a cookie?

Cookie are one of several ways to store data about web site visitors during the time when web server and browser are not connected. Common use of cookies is to remember users between visits. Practically, cookie is a small text file sent by web server and saved by web browser on client machine

For example, when visitor comes to your web site you can store information about last visit and retrieve that information when visitor comes next time.

To write a cookie in ASP.NET we can use a code like this:


‘ Add this on the beginning of your .vb code file
Imports System.Web

‘ Use this line to save a cookie
Response.Cookies("MyCookieName").Value = "MyCookieValue"

‘ How long will cookie exist on client hard disk
Response.Cookies("MyCookieName").Expires = Now.AddDays(1)

‘ To add multiple key/value pairs in single cookie
Response.Cookies("VisitorData")("FirstName") = "BCAHUB"
Response.Cookies("VisitorData")("LastVisit") = Now.ToString()


To read a cookie value, use this:

Dim MyCookieValue As String
‘ We need to perform this check first, to avoid null exception
‘ if cookie not exists

If Not Request.Cookies("MyCookieName") Is Nothing Then
MyCookieValue = Request.Cookies("MyCookieName").Value

End If

How to delete cookie in ASP.NET
To delete existing cookie we actually just set its expiration time to some time in the past. You can do it with code like this:


‘ First check if cookie exists

If Not Request.Cookies("MyCookieName") Is Nothing Then

‘ Set its expiration time somewhere in the past

Response.Cookies("MyCookieName").Expires = Now.AddDays(-1)

End If



About the Author

Akash Padhiyar

Visit Website

There are no comments yet, add one below.

Leave a Comment

Your email address will not be published. Required fields are marked *


Time limit is exhausted. Please reload CAPTCHA.