SetCookie and GetCookie in WPF Application

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=Mahesh;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);

     

Listing 1

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);

 

Listing 2