Sign in to follow this  

[.net] Retrieve a cookie from the harddrive, C#

Recommended Posts

I'm currently writing an application which is supposed to get some data from a webpage. In order to do that I want to use a cookie which is saved on the harddrive. Is it possible to load a cookie which is stored from the harddrive, or do I have to create them myself? The c#-pseuode code below should explain what i want..
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("some url");

Cookie cookie = new Cookie();

cookie = a cookie save in c:\documents and settings\username\cookies\something.txt

req.CookieContainer = new CookieContainer();

System.Net.WebResponse r = req.GetResponse();
Stream s = r.GetResponseStream();
StreamReader sr = new StreamReader(s);
string st = sr.ReadToEnd();

Share this post

Link to post
Share on other sites

You have to make a persistent cookie, so you have to set an expiration date. If you do not do that, it will automatically become a temporary cookie.

Create like this:

HttpCookie objCookie = new HttpCookie("MyCookie");
DateTime now = DateTime.Now;

//The following code adds a pair of keys and values:
objCookie.Values.Add("Time", now.ToString());
objCookie.Values.Add("ForeColor", "White");
objCookie.Values.Add("BackColor", "Blue");

//The following code sets the expiration time of the cookie to one hour:
objCookie.Expires = now.AddHours(1)


And retrieve the cookie like this:

HttpCookie objCookie = Request.Cookies["myCookie"];
lblTime.Text = objCookie.Values["Time"];
lblTime.BackColor = System.Drawing.Color.FromName

Hope this helps,


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this