Saturday, March 24, 2012

Trouble with changing a value in a cookie.

I wanted to change a value in a existing cookie. I read the old value, modify it and to write the new value in the old cookie. Here is the code:

public bool SetCookie(string cookiename, string cookievalue, int iDaysToExpire) //create the cookie
{
try
{
HttpCookie objCookie = new HttpCookie(cookiename);
Response.Cookies.Clear();
Response.Cookies.Add(objCookie);
objCookie.Values.Add(cookiename, cookievalue); // adding the value to the cookie
DateTime dtExpiry = DateTime.Now.AddDays(iDaysToExpire); //expires
Response.Cookies[cookiename].Expires = dtExpiry;
}
catch (Exception e)
{
return false;
}
return true;
}

public string GetCookie(string cookiename)// method which gives the value from the cookie
{
string cookyval = "";
try
{
cookyval = Request.Cookies[cookiename].Value;
}
catch (Exception e)
{
cookyval = "";
}
return cookyval;
}

protected void Page_Load(object sender, EventArgs e)
{

String t, s,t1;
int i = 0;
s = "";
t = "";

t = GetCookie("test");//reading the cookie
//removing the name and getting the value
try
{
lbl1.Text = t; //
t1 = t.Remove(0, 9);
i = Int32.Parse(t1);
i = i + 1; //the value is modified
}
catch (Exception w) { lbl3.Text = "Convert isnt working."; }
s = Convert.ToString(i);

//writing the new value in the cookie
SetCookie("test", s, 1);

//testing to see if the new value is written
t1 = GetCookie("test");
lbl2.Text = s;
lbl3.Text = t1;
}
}What is your question, exactly? This code re-sets the cookie each time it runs. It seems to return exactly what you're setting it to ("test=0"). (Is that the value that you want it to have?)

0 comments:

Post a Comment