Link to home
Start Free TrialLog in
Avatar of rfranquet
rfranquet

asked on

Downloading a file in C# with cookies

I wont write a code in C#, for download a file fom a URI with a login cookie.

If I don’t need cookies, is very easy,

string uriString;
     
uriString = "http://www.eoddata.com/";

WebClient myWebClient = new WebClient();
Stream myStream = myWebClient.OpenRead(uriString);

StreamReader reader = new StreamReader(myStream);
StreamWriter writer = new StreamWriter("outfile.htm");

writer.WriteLine(reader.ReadToEnd());

myStream.Close();
reader.Close();
writer.Close();

It works in a normal URI, but when the URI won to identify the user, I don’t know how the server ask me the cookie, how can I find it, how can I send it and how can I download the file.

For example this URI
http://www.eoddata.com/Data.asp?e=AMEX&d=2004Feb12 

I can access though the internet explorer, the cookie is in the system, but this code does not use this cookie.

Can you help me? Please.


Avatar of jrberg
jrberg

Here ya go,  I just wrote this up and tested it for ya.  Hope you like it.

      // Create Target
      string destination = "http://www.eoddata.com/";
     
      // Create a WebRequest object and assign it a cookie container and make them think your Mozilla ;)
      CookieContainer cookies = new CookieContainer();
      HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(destination);
      webRequest.Method = "GET";
      webRequest.Accept = "*/*";
      webRequest.AllowAutoRedirect = false;
      webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)";
      webRequest.CookieContainer = new CookieContainer();
      webRequest.ContentType = "text/xml";
      webRequest.Credentials = null;  
      webRequest.CookieContainer.Add(cookies.GetCookies( new System.Uri(destination)));

      // Grab the response from the server for the current WebRequest
      HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
     
      // Wrap it in a streamreader so you dont have to go byte by byte
      TextReader tr = new StreamReader( webResponse.GetResponseStream() );

      // Wa-La.
      Console.WriteLine( tr.ReadToEnd() );
ASKER CERTIFIED SOLUTION
Avatar of mogun
mogun

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rfranquet

ASKER

Thank You.

This really works.

Now Starts another problem.

Really Thank You Very Much.
===================
Mine did not work?  I tried it and it seemed to work. Hmmm.
Sorry, but with your code,  when you try to download without login (or when the login fails), the server sends this html file.

thank you for your answer.