There are
two types of cookies - session cookies and persistent cookies. Session cookies
data is available during an application session only and once the session is
expired, the cookie is deleted.
Persistent cookies on the other hand are
stored in the Temporary Internet Files folder and can be stored for longer time
and the life time of these cookies are set within the cookie data as an
expiration date and time.
A cookie
data is in the name and value pair format where NAME=VALUE. Here is an example
of a cookie data.
"UserName=hitendra"
If a cookie
data has expires data followed by a semi colon in it, it is considered as a
persistent cookie. Here is an example of a persistent cookie. Here is the
format of a persistent cookie.
NAME=VALUE;
expires=DAY, DD-MMM-YYYY HH:MM:SS GMT
Here is an
example of a persistent cookie data.
"UserName=Mahesh;
expires=Friday, 10-Dec-2010 00:00:00 GMT"
Application.SetCookie
method creates a cookie on users' machine. This method takes two parameters -
an Uri and a string. The first parameter, the Uri specifies a location where
the cookie will be created at and second parameter is a cookie data.
Code snippet
in Listing 1 creates two cookies using SetCookie method. One is a session
cookie and other is a persistent cookie.
string
simpleCookie = "CSCUser1=Mahesh";
string
cookieWithExpiration = "CSCUser2=hitendra;expires=Sat,
10-Oct-2012 00:00:00 GMT";
Uri
cookieUri1 = new Uri(@"C:\Junk\SimpleMC");
Uri
cookieUri2 = new Uri(@"C:\Junk\PersMC");
Application.SetCookie(cookieUri1,
simpleCookie);
Application.SetCookie(cookieUri2, cookieWithExpiration);
Application.SetCookie(cookieUri2, cookieWithExpiration);
Application.GetCookie
method retrieves cookie data from the given Uri.
The code
listed in Listing 2 uses the GetCookie method to get the cookie data and
displays it in a MessageBox.
Uri
cookiePath = new Uri(@"C:\Junk\MC");
string
cookie = Application.GetCookie(cookiePath);
MessageBox.Show(cookie)