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

Started by
3 comments, last by edotorpedo 18 years, 5 months ago
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();
req.CookieContainer.add(cookie);

System.Net.WebResponse r = req.GetResponse();
Stream s = r.GetResponseStream();
StreamReader sr = new StreamReader(s);
string st = sr.ReadToEnd();
Advertisement
This is pretty .NET-specific, so I'm moving it there.
- k2"Choose a job you love, and you'll never have to work a day in your life." — Confucius"Logic will get you from A to B. Imagination will get you everywhere." — Albert Einstein"Money is the most egalitarian force in society. It confers power on whoever holds it." — Roger Starr{General Programming Forum FAQ} | {Blog/Journal} | {[email=kkaitan at gmail dot com]e-mail me[/email]} | {excellent webhosting}

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)Response.Cookies.Add(objCookie);


And retrieve the cookie like this:

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


Hope this helps,

Edo
Edo
Thanx the help! Unfortunately it doesn't help since i'm not coding a webpage. If I'm not misstaken the Request object is only a part ASP.NET.


Hmmm... not quite sure what you want then.. but have a look at this:

Click
Edo

This topic is closed to new replies.

Advertisement