Why in my WebClient DownloadFileAsync method downloading an Empty File?

c# download file from server
c# download file from url without filename
c# httpclient download file
download file c# console application
c# download file and run it
async await download file c
file download complete event c#
wpf download file

I have this C# code but the final esi.zip results in 0 length or basically empty. The URL does exist and confirms to download the file manually. I am baffled buy this.

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)

Thanks

UPDATED: I updated the code where no spaces exist at all but it still downloads 0 bytes.

Here's the working code. There were 2 things you were not doing, that was causing the 0 byte file to be downloaded.

  1. 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.
  2. 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.

WebClient.DownloadFile Method (System.Net), The DownloadFile method downloads to a local file data from the URI specified by If the BaseAddress property is not an empty string ("") and address does not � StackOverflow Q: 26534980 Solution - Why in my WebClient DownloadFileAsync method downloading an Empty File? | Test your C# code online with .NET Fiddle code editor.

 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) { }

Code Editor, public static void DownloadFile(). 14 WebClient downloader = new WebClient ();. 17 DownloadFileAsync(new Uri(url), "C:\\all_surveys_total_sa_nace2.zip");. This method downloads the resource at the URI specified by in the address parameter. When the download completes successfully, the downloaded file is named fileName on the local computer. The file is downloaded asynchronously using thread resources that are automatically allocated from the thread pool.

Although this is an old thread, the so far given answers might not be sufficient to solve the "empty file" problem.

In case you are downloading from a https secure site, the "DownloadComplete" callback could indicate an error-free download, nevertheless the downloaded file might be empty. In my case, the advice given here helped. After adding the following line the download was ok:

    System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
    webClient.DownloadFileAsync(new System.Uri(link), savePath);

Empty dll and exe files are getting loaded by using , Varun Check the setting for the firewall on your system. That might be causing this. This method works fine for dll and exes. I have this� This method downloads the resource at the URI specified by in the address parameter. Une fois le téléchargement terminé, le fichier téléchargé est nommé fileName sur l’ordinateur local. When the download completes successfully, the downloaded file is named fileName on the local computer.

Adding this worked very fine for me! Thanks!

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

How to download a file from a URL in C#?, Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this Check for a network connection using GetIsNetworkAvailable() to avoid creating empty files when not � Remarks. The DownloadFile method downloads to a local file data from the URI specified by in the address parameter. This method blocks while downloading the resource. To download a resource and continue executing while waiting for the server's response, use one of the DownloadFileAsync methods.

client, I don't see the progress bar, the Completed event doesn't fire and the file downloads instantly (even if its large), and is just completely empty. I've� In this case we are going to use the WebClient.DownloadFileAsync method /// <summary> /// Download a file asynchronously in the desktop path, show the download progress and save it with the original filename.

How to download a webfile with C# and show download progress , The most easy way to download a file syncronously (will freeze the UI), thanks to you should understand how the DownloadFile method works. You can use a little trick to prevent the creation of empty files in case there's� I am trying to download a file using simple basic webclient instructions, however the file is not downloading completing. If I am trying to download a 10mb/100mb file, it either downloads a 7kb file or an empty file. I am just using a ProgressBar to show the download progress. Here is the code that I am using.

WebClient.DownloadFile C# (CSharp) Code Examples, These are the top rated real world C# (CSharp) examples of WebClient. Method/Function: DownloadFile WriteLine("The application can not download the file!!!"); } } WriteLine("Invalid address/ filename-null reference(empty)/ error while� Just my guess: maybe you can try to keep the WebClient instance in some place would not be garbage collected. When the DownloadFileCompleted event fired, you just clean the reference to the WebClient instance and let GC to reclaim the memory later (and don't forget to call Dispose method).

Comments
  • Is that giant space in the image URL supposed to be there? Or is it there in your code? Does removing that space fix the problem?
  • Did you wait for the DownloadFileCompleted event?
  • there is no space in the code, it just seems adding this stackoverflow can be strange. Shiva, can you send over the entire C# file so I can see wbere my end is wrong? Thanks
  • Check out the code here => dotnetfiddle.net/vjZAe2 The fiddle won't run because of FileIOSecurityException. But drop this code in your local console app. That's what I did, and it runs, and saves the file, but it is 0 bytes like you said. Very strange.
  • I fixed it. Able to download the code. Will post it. You have to call IsBusy on the WebClient to wait for it to download. Also, if you don't specify a browser user-agent, that URL / site returns a 502 Bad Gateway.
  • I prefer Mohsin Kahn's answer, but +1 for the user agent.
  • while (downloader.IsBusy) { } - This resolved my problem.
  • I think this response deserves more attention! Simple but works.