C# get or set cookies, to download content from the web using cookies

qdza picture qdza · Jul 23, 2011 · Viewed 17.5k times · Source

I need help with cookies. I'm planing use cookies to download web content. To get the content I need to log into a website because only authorized users can download web content or files. I'm using

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

and then I'm scraping source code, and I need to get link to file, but I can't get because I'm not authorized, so I need to set cookies. I have not worked with cookies before. How do I to do this?

Answer

user619891 picture user619891 · Jul 23, 2011

If you are talking about creating a asp.net web app that can create cookies, then doing this should work:

Not sure if this would work in asp.net mvc though, this works in asp.net web forms

Response.Cookies["nameOfCookie"].Value = "someValue";
Response.Cookies["nameOfCookies].Expires = DateTime.Now.AddDays(1);

then on a post back on say same page or different page, can get cookie by

string value = string.Empty;
if (Request.Cookies["nameOfCookie"] != null)    
    value = Request.Cookies["nameOfCookie"].Value;