Tuesday, April 21, 2009

How to store and read Cookies in asp.net/C#.

How to store and read Cookies in asp.net/C#.

We can have requirement to store cookies in client machine for later use. we can use HttpCookie Class to do this task.

How to Store:
this function will save them on client machine.

private void SetCookies()
{
HttpCookie SearchCookies = new HttpCookie("SearchCookies");
SearchCookies.Expires = DateTime.Now.AddMonths(1);
SearchCookies.Values.Add("Range", radComboRange.SelectedIndex.ToString());
Response.Cookies.Add(SearchCookies);
}



How to Read:
this function will read from Request Object(client machine) and Save cookie value in ViewState.


private void GetCookies()
{
HttpCookie SearchCookies = Request.Cookies["SearchCookies"];
if (SearchCookies != null)
{
if (SearchCookies.Values["Range"] != null)
{
ViewState["Range"] = radComboRange.SelectedIndex = int.Parse(SearchCookies.Values["Range"]);
}
}
}


Thanks.