How to store cookie permanently

16.3k views Asked by At

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>
3

There are 3 answers

2
Satinder singh On BEST ANSWER

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
 }
0
AudioBubble On
        HttpCookie Cookie = new HttpCookie("cksunlightitmailid");
        Cookie.Value = txtSunlightitmailid.Text.Trim();
        Cookie.Expires = DateTime.MaxValue; // never expire
        HttpContext.Current.Response.Cookies.Add(Cookie);
        HttpCookie ck_d = Request.Cookies["cksunlightitmailid"];
if (Request.Cookies["cksunlightitmailid"] != null)
        {
            lblSunlightitmailid.Text = "Ur current email id :" + Request.Cookies["cksunlightitmailid"].Value;
            //Or Write ur own code here
        }
1
Rahul Nikate On
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();
}