[英]Downloading file without direct link through C# Webclient
我正在嘗試下載文件,但問題是 url 不是 zip 文件的直接鏈接,我的代碼給了我無用的錯誤
這是代碼
var zipFile = new FileInfo(Path.Combine(directory.FullName, "temp.zip"));
var progressInfo =
new ProgressBarInfo(
$"{DateTime.Now:dd-MM-yyyy HH:mm:ss.ffff}\t[PROGRESS] Download IP2Location database");
UiManager.UiImplementation.ShowProgressBar(progressInfo);
try
{
using (var webClient = new WebClient { Proxy = null })
{
var url = $"https://www.ip2location.com/download/?token={downloadToken}&file={DatabaseProduct}";
webClient.DownloadProgressChanged +=
(sender, args) =>
progressInfo.ReportProgress(args.ProgressPercentage / 100d);
using (var autoResetEvent = new AutoResetEvent(false))
{
webClient.DownloadFileCompleted += (sender, args) => autoResetEvent.Set();
webClient.DownloadFileAsync(new Uri(url), zipFile.FullName);
autoResetEvent.WaitOne();
}
}
}
finally
{
progressInfo.Close();
}
如果我將 url 變量更改為直接鏈接,例如: https://speed.hetzner.de/10GB.bin那么代碼工作正常
if i visit this url https://www.ip2location.com/download/?token=REDACTED&file=DB11LITE it will directly download a file named IP2LOCATION-LITE-DB11.CSV.ZIP
這是我在瀏覽器中訪問 url 時的響應 header
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 13 Dec 2021 23:22:15 GMT
Content-Type: application/zip
Content-Length: 48726637
Connection: keep-alive
Expires: 0
Cache-Control: must-revalidate, post-check=0, pre-check=0
Pragma: public
Cache-Control: private
Content-Disposition: attachment; filename="IP2LOCATION-LITE-DB11.CSV.ZIP"
Content-Transfer-Encoding: binary
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Referrer-Policy: no-referrer-when-downgrade
Content-Security-Policy: default-src * data: 'unsafe-eval' 'unsafe-inline';frame-ancestors 'self';
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
需要注意的是, Webclient
class 使用 RETR 命令下載 FTP 資源。 對於 HTTP 資源,使用 GET 方法。 這意味着如果您提供的 URL 不包含可下載文件的正確參數,您最終會遇到一些未處理的異常,因為Webclient
已替換為System.Net.Http.HttpClient
,我建議您改用.
在下面,您可以看到Webclient
如何工作的示例,在您的情況下,您會收到“無用的錯誤”,因為您使用的是異步方法。 我建議使用如下的常規方法來調試並獲得正確的異常。
public void downloadProgrambyURL(string url, string filename)
{
using (WebClient client = new WebClient())
{
var pathVariable = "%USERPROFILE%\\Downloads\\" + filename;
var filePath = Environment.ExpandEnvironmentVariables(pathVariable);
client.DownloadFile(url, filePath);
}
}
另外,我會讓這個鏈接供您參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.