Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

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.

Example

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.Cookies.Add(myCookie);

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.

Security

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

Show:
© 2015 Microsoft