18

I want to store the username in the cookie and retrieve it the next time when the user opens the website. Is it possible to create a cookie which doesnt expires when the browser is closed. I am using asp.net c# to create the website. And how can I stop the browser from offering to save username and password

Murthy
  • 1,502
  • 11
  • 31
  • 45
  • Please check this http://stackoverflow.com/questions/8485186/how-to-set-remember-me-in-login-page-without-using-membeship-in-mvc-2-0/8485215#8485215 – Dewasish Mitruka Dec 13 '11 at 11:51

2 Answers2

40

Writing a cookie

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.AddYears(50); // For a cookie to effectively never expire

// Add the cookie.
Response.Cookies.Add(myCookie);

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

Reading a cookie

HttpCookie myCookie = Request.Cookies["MyTestCookie"];

// Read the cookie information and display it.
if (myCookie != null)
   Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
   Response.Write("not found");
Shai
  • 25,159
  • 9
  • 44
  • 67
7

In addition to what Shai said, if you later want to update the same cookie use:

HttpCookie myCookie = Request.Cookies["MyTestCookie"];
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = now.ToString();

// Don't forget to reset the Expires property!
myCookie.Expires = now.AddYears(50);
Response.SetCookie(myCookie);
Tomas Beblar
  • 468
  • 4
  • 18
Joe.P
  • 319
  • 4
  • 10