Search code examples
c#downloadauthorizationwebclient

WebClient DownloadFile with Authorization not working


I have tried just about everything I can think of to get this to work, including several things I've found online. All I'm trying to do is download a file (which has a direct link) from a website that I have to log in to.

I tried doing the following, with the "UploadValues":

WebClient myWebClient = new WebClient();
NameValueCollection myNameValueCollection = new NameValueCollection();
myNameValueCollection.Add("username", this.UserName);
myNameValueCollection.Add("password", this.Password);
byte[] responseArray = myWebClient.UploadValues(felony, myNameValueCollection);
myWebClient.DownloadFile(felony, localfelony);

and I've also tried putting the login info in the headers as well. I've also tried just setting the credentials, as you can see from the commented code:

WebClient client = new WebClient();
//client.UseDefaultCredentials = false;
//client.Credentials = new NetworkCredential(this.UserName, this.Password);
client.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(this.UserName + ":" + this.Password)));
client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
//client.Headers.Add(HttpRequestHeader.Cookie, this.webBrowser.Document.Cookie);
client.DownloadFile(felony, localfelony);

No matter what I try, the only thing I can get it to download is a file that ends up being the login page, as if it didn't accept the login info I passed.

I've looked at the headers and such, and I don't see anything out of the ordinary that would explain why this isn't working. Any ideas?


Solution

  • I could swear I had tried this before, but I guess maybe I had it just a little different or something. So it worked like this:

    WebClient client = new WebClient();
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential(this.UserName, this.Password);
    client.Headers.Add(HttpRequestHeader.Cookie, "_gat=1; b46467afcb0b4bf5a47b2c6b22e3d284=mt84peq7u4r0bst72ejs5lb7p6; https://docs.stlucieclerk.com/=1,1; _ga=GA1.2.12049534.1467911267");
    client.DownloadFile(webaddress, localname);
    

    It was the cookie in the header that made it work. I thought I'd done that before, but maybe I did something involving a cookie that was different.