1
WebClient ws = new WebClient();
ws.Credentials = new System.Net.NetworkCredential(username, password, domain);
 ws.DownloadFile("https://xxxx.xxxx.com/xxxx.xml", @"C:\Windows\TEMP\Downloaded.xml");

I got error 'Object reference not set to an instance of an object'. Anyone know why?

If I copy the "https://xxxx.xxxx.com/xxxx.xml" to browser, it can download and save to "C:\Windows\TEMP\Downloaded.xml", but my program can not, only throw the error.

Previously I use the same code successfully download the file, but that was another site with 'http'. Not sure whether it's the cause of the problem.

nixjojo
  • 617
  • 8
  • 22

2 Answers2

1

I hade the same issue when using the WebClient class. What I did was build an URI instead of the string path like this (I've not done it here, but you can also add username and password to the UriBuilder):

var uriBuild = new UriBuilder { Host host, Path = downloadPath };
client.DownloadFileAsync(uriBuild.Uri, localPath);

The host and download path is seperated, for example:

string host = "ftp.sunet.se"
string downloadPath = "/pub/unix/databases/relational/mysql/Downloads/MySQL-5.5/mysql-5.5.22-win32.msi"

Let me know if this also works for you! Cheers :)

Amadeus Hein
  • 706
  • 1
  • 4
  • 12
0

use uri instead of using original url

Uri URL = urlAddress.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("https://" + urlAddress);
await myWebClient.DownloadFileTaskAsync(URL, location);
Herahadi An
  • 198
  • 14