HttpCookie cookie = new HttpCookie("Preferences");
// Set a value in it.
cookie["LanguagePref"] = "English";
// Add another value.
cookie["Country"] = "US";
// Add it to the current web response.
A cookie added in this way will persist until the user closes the browser and will be sent with every request. To create a longer-lived cookie, you can set an expiration date:
cookie.Expires = DateTime.Now.AddYears(1);
You retrieve cookies by cookie name using the Request.Cookies collection:
// Check to see whether a cookie was found with this name.
// This is a good precaution to take,
// because the user could disable cookies,
// in which case the cookie will not exist.
if (cookie != null)
language = cookie["LanguagePref"];
The only way to remove a cookie is by replacing it with a cookie that has an expiration date that has already passed. This code demonstrates the technique:
cookie.Expires = DateTime.Now.AddDays(-1);