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");

我收到错误“对象引用未设置为对象的实例”。有谁知道为什么?

如果我将“https://xxxx.xxxx.com/xxxx.xml”复制到浏览器,它可以下载并保存到“C:\Windows\TEMP\Downloaded.xml”,但我的程序不能,只能抛出错误。

以前我使用相同的代码成功下载了文件,但那是另一个带有“http”的站点。不确定是否是问题的原因。

4

2 回答 2

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 :)

于 2012-04-24T10:37:46.177 回答
0

使用 uri 而不是使用原始 url

Uri URL = urlAddress.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("https://" + urlAddress);
await myWebClient.DownloadFileTaskAsync(URL, location);
于 2021-10-14T22:46:31.587 回答