11

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.

Shiva
  • 20,575
  • 14
  • 82
  • 112
heavy rocker dude
  • 2,271
  • 8
  • 33
  • 47
  • 2
    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? – trnelson Oct 23 '14 at 18:38
  • 2
    Did you wait for the [`DownloadFileCompleted`](http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadfilecompleted(v=vs.110).aspx) event? – Marc Gravell Oct 23 '14 at 18:39
  • 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 – heavy rocker dude Oct 23 '14 at 18:57
  • Check out the code here => https://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. – Shiva Oct 23 '14 at 19:02
  • 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`. – Shiva Oct 23 '14 at 19:10
  • Awesome Shiva, i await your code samplng. Hopefully this can help others as you helped me definitely. – heavy rocker dude Oct 23 '14 at 19:14
  • Just posted it. Check it out. – Shiva Oct 23 '14 at 19:24
  • I get `502 Bad Gateway` - check Shiva's example for spoofing a web browser request. Very cool! – Rufus L Oct 23 '14 at 19:24

4 Answers4

17

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.

Shiva
  • 20,575
  • 14
  • 82
  • 112
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) { }
Pawel Gradecki
  • 3,476
  • 6
  • 22
  • 37
Mohsin Khan
  • 175
  • 11
0

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);
josh
  • 671
  • 5
  • 10
-1

Adding this worked very fine for me! Thanks!

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