我有这个C#代码,但最终的esi.zip导致0长度或基本为空。 URL确实存在并确认手动下载文件。我很困惑买这个。
string zipPath = @"C:\download\esi.zip";
Client.DownloadFileAsync(new Uri("http://ec.europa.eu/economy_finance/db_indicators
/surveys/documents/series/nace2_ecfin_1409/all_surveys_total_sa_nace2.zip"), zipPath)
谢谢
更新:我更新了根本不存在空格但仍然下载0字节的代码。
答案 0 :(得分:10)
这是工作代码。你有两件事没有做,导致0
字节文件被下载。
IsBusy
。这需要调用,以便代码等待当前线程完成,因为异步操作将在新线程上。创建一个空白控制台应用程序并将以下代码放入其中并试用。
namespace TestDownload
{
class Program
{
static void Main(string[] args)
{
string sourceUrl = "http://ec.europa.eu/economy_finance/db_indicators/surveys/documents/series/nace2_ecfin_1409/all_surveys_total_sa_nace2.zip";
string targetdownloadedFile = @"C:\Temp\TestZip.zip";
DownloadManager downloadManager = new DownloadManager();
downloadManager.DownloadFile(sourceUrl, targetdownloadedFile);
}
}
}
using System;
using System.ComponentModel;
using System.Net;
namespace TestDownload
{
public class DownloadManager
{
public void DownloadFile(string sourceUrl, string targetFolder)
{
WebClient downloader = new WebClient();
// fake as if you are a browser making the request.
downloader.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");
downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(Downloader_DownloadFileCompleted);
downloader.DownloadProgressChanged +=
new DownloadProgressChangedEventHandler(Downloader_DownloadProgressChanged);
downloader.DownloadFileAsync(new Uri(sourceUrl), targetFolder);
// wait for the current thread to complete, since the an async action will be on a new thread.
while (downloader.IsBusy) { }
}
private void Downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// print progress of download.
Console.WriteLine(e.BytesReceived + " " + e.ProgressPercentage);
}
private void Downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
// display completion status.
if (e.Error != null)
Console.WriteLine(e.Error.Message);
else
Console.WriteLine("Download Completed!!!");
}
}
}
完成后,您应该在targetdownloadedFile
变量中指定的位置看到zip文件,在本例中,该变量位于本地计算机上的C:\Temp\TestZip.zip
。
答案 1 :(得分:1)
objFeedBO = new FeedBO();
string strfilename = System.IO.Path.GetFileName(url);
FileStream outputStream = new FileStream(DownloadPath + "\\" + strfilename, FileMode.Create);
string targetdownloadedFile = @"D:\TestZip.php";
WebClient myWebClient = new WebClient();
myWebClient.DownloadFileAsync(new Uri(url), targetdownloadedFile);
while (myWebClient.IsBusy) { }
答案 2 :(得分:0)
尽管这是一个旧线程,但到目前为止给出的答案可能不足以解决“空文件”问题。
如果您是从 https 安全站点下载的,则“ DownloadComplete”回调可能表示无错误下载,但是下载的文件可能为空。 就我而言,here的建议有所帮助。添加以下行后,下载正常:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
webClient.DownloadFileAsync(new System.Uri(link), savePath);
答案 3 :(得分:-1)
添加此功能对我来说很好!谢谢!
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;