How to store cookie permanently

14,873

Solution 1

pseudo code:

Code to ADD cookie

HttpCookie e = new HttpCookie("d");
e.Value = "set-Email-Id";
e.Expires = DateTime.Now.AddDays(30); // expires after 30 days
HttpContext.Current.Response.Cookies.Add(e);

Code to Read ( get ) cookie by it name

HttpCookie ck_d = Request.Cookies["d"];
 if(ck_d!=null)
 {
     // logic here
 }

Solution 2

string MailID = ConfigurationManager.AppSettings["MailId"];

Create a cookie

HttpCookie mailCookie= new HttpCookie("mailCookie");

Add key-values in the cookie

mailCookie.Values.Add("MailID", MailID);

set cookie expiry date-time. Keep it max value.

mailCookie.Expires = DateTime.MaxValue;

Most important, write the cookie to client.

Response.Cookies.Add(mailCookie);

Read the cookie from Request.

HttpCookie mailCookie= Request.Cookies["mailCookie"];
if (mailCookie== null)
{
    //No cookie found or cookie expired.
}

Cookie is found.

if (!string.IsNullOrEmpty(mailCookie.Values["MailID"]))
{
    string MailID= mailCookie.Values["MailID"].ToString();
}
Share:
14,873
Rahul Nikate
Author by

Rahul Nikate

A Software Engineer by Heart, Mind and Profession....! Currently I'm actively involved in MVC.Net, C#, ASP.Net, JavaScript, JQuery, AngularJS, Bootstrap, Restful, SQL Server, sometimes windows stuff. You can reach me at [email protected] SOreadytohelp

Updated on June 04, 2022

Comments

  • Rahul Nikate
    Rahul Nikate almost 2 years

    I don't want to show mail id in my application code. I want to give text box and what ever email id I will give it should be stored in web.config file for ever until I change it.

    string store= "[email protected]";
    ConfigurationManager.AppSettings["MailId"] = store;
    string message1 = ConfigurationManager.AppSettings["MailId"];
    
    <appSettings>
        <add key="aspnet:MaxHttpCollectionKeys" value="2001"/>
        <add key="MailId" value="[email protected]" />
    </appSettings>
    
  • Admin
    Admin almost 9 years
    i want to store mail id . in this how to store mailid. can u write code form me. lets assume my mail id "[email protected]"@satinder singh
  • Admin
    Admin almost 9 years
    hai how to change mail id . where is text box.how can i change emailid@Rahul Nikate
  • Satinder singh
    Satinder singh almost 9 years
    @RahulNikate: That was pseudo code have already mentioned above, though i updated my answer