This documentation is archived and is not being maintained.

Code: Writing a Cookie (Visual C#)

Visual Studio .NET 2003

The following example uses the HttpCookie class and its properties to write a cookie that expires after one minute.


HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);

// Add the cookie.

Response.Write("<p> The cookie has been written.");

Compiling the Code

Start a new ASP.NET Web application and paste the code into the Page_Load method.

Robust Programming

Replace the name "MyTestCookie" and the cookie value with a name and value of your choice.


Information stored in a cookie can be lost because the user has full control over cookies and can disable cookies entirely.

See Also

Code: Reading a Cookie (Visual C#) | HttpCookie Class | Web Applications Example Topics