1

I am trying to make a cURL call to download a CSV file and I'm getting back the login page html. Here is the code:

WebRequest myRequest = WebRequest.Create("https://website.com/medias/823533/events.csv");
        myRequest.Credentials = new NetworkCredential("username", "password");
        myRequest.Method = "GET";
        myRequest.PreAuthenticate = true;
        // Return the response. 
        WebResponse myResponse = myRequest.GetResponse();
        StreamReader sr = new StreamReader(myResponse.GetResponseStream());
        string result = sr.ReadToEnd();
        sr.Close();
        Console.WriteLine(result);
        Console.ReadLine();

Is there a simple cURL method in C#? This doesn't seem to be working no matter what I try.

svick
  • 236,525
  • 50
  • 385
  • 514
Sam Cromer
  • 687
  • 3
  • 12
  • 31
  • 4
    This is not cURL, instead it is a [WebRequest](http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx). Are you getting any errors? How is it not working? – drew010 Mar 22 '12 at 18:36
  • When you say cURL do you mean something like [Using curl with Phalanger](http://stackoverflow.com/questions/1707053/using-curl-with-phalanger) or do you mean cURL c# equivilent – Conrad Frix Mar 22 '12 at 18:44
  • I found the issue, the @ sign in the username had to be converted to Base64, I'll post the code once the site lets me answer my own question in 7 hours... :) – Sam Cromer Mar 22 '12 at 19:07
  • @SamCromer better just to amend your question. – Slugart Mar 22 '12 at 19:10
  • possible duplicate of [cURL call in C#](http://stackoverflow.com/questions/9825846/curl-call-in-c-sharp) – svick Mar 22 '12 at 20:47
  • Please don't post the same question twice. If you have some new information, edit your old question. – svick Mar 22 '12 at 20:47

1 Answers1

2

I found the issue. Apparently the request fails when you pass an "@" sign ( like in the email username ) in the username field so it must be Converted to a base 64 string. Here is the code just incase someone else runs into this:

        string url = "https://website.com/events.csv";
        WebRequest myReq = WebRequest.Create(url);

        string username = "username";
        string password = "password";
        string usernamePassword = username + ":" + password;
        CredentialCache mycache = new CredentialCache();
        mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
        myReq.Credentials = mycache;
        myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

        WebResponse wr = myReq.GetResponse();
        Stream receiveStream = wr.GetResponseStream();
        StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
        string content = reader.ReadToEnd();
        Console.WriteLine(content);
        Console.ReadLine();
afzalulh
  • 7,925
  • 2
  • 26
  • 37
Sam Cromer
  • 687
  • 3
  • 12
  • 31