Why in my WebClient DownloadFileAsync method downloading an Empty File?
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) { }
Here's the working code. There were 2 things you were not doing, that was causing the 0
byte file to be downloaded.
- You were not calling
IsBusy
. That needs to be called in order for the code to wait for the current thread to complete, since the an async action will be on a new thread. - The Site in question was returning a badgateway, unless you spoof the request as if it's coming from a regular web browser.
Create a blank console app and put the following code in it and try it out.
Paste this code into Program.cs file of the blank/new console app.
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);
}
}
}
Add a new C# class file called DownloadManager and drop this code in it.
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!!!");
}
}
}
Now Build and run the console app. You should see the progress in the console output window like so.
And when it's complete, you should see the zip file in the location specified in the targetdownloadedFile
variable, which in this example is at C:\Temp\TestZip.zip
on your local machine.