1

I am trying to download a test.exe file with this code:

public void DownloadFile()
{
    using(var client = new WebClient())
    {
         client.DownloadFileAsync(new Uri("http://www.acromix.net16.net/download/test.exe"), "test.exe");
    }
}

With this simple code, I debug it and this was the output: output

I don't know and have no idea why it is 0 KB (should be 328 KB). [/downloads]

How can I make it work?

EDIT: The hosting site (000webhost) blocks .exe files to download...

newbieguy
  • 658
  • 2
  • 11
  • 29
  • 2
    Why are you using the `Async` version? – SimpleVar Oct 04 '15 at 09:10
  • Check out this article at Microsoft. It is a asynchronous downloading program written in C# that will help you. https://code.msdn.microsoft.com/windowsdesktop/Asynchronous-Downloader-61955c78 – Kerry Kobashi Oct 04 '15 at 09:24

3 Answers3

5

The issue is that you are using DownloadFileAsync which is an async version. To know when download is complete you have to subscribe to DownloadFileCompleted event.

Either use sync method:

public void DownloadFile()
{
    using(var client = new WebClient())
    {
        client.DownloadFile(new Uri("http://www.acromix.net16.net/download/test.exe"), "test.exe");
    }
}

Or use new async-await approach:

public async Task DownloadFileAsync()
{
    using(var client = new WebClient())
    {
        await client.DownloadFileTaskAsync(new Uri("http://www.acromix.net16.net/download/test.exe"), "test.exe");
    }
}

Then call this method like this:

await DownloadFileAsync();
xZ6a33YaYEfmv
  • 1,816
  • 4
  • 24
  • 43
1

WebClient.DownloadFileAsync uses an Event-based Asynchronous Pattern and, as any XXXAsync WebClient that predates async-await, requires subscribing to a XXXCompleted event. So, in the case of DownloadFile the DownloadFileCompleted should be subscribed to wait for the completion of the download.

With the advent of async-await comes the Task-based Asynchronous Pattern (TAP). Usually, TAP methods are suffixed Async, but since there were already Async sufixed members in the class, the second rules applies and the methods are suffixed TaskAsync.

Since the OP tagged the question with async-await, the correct code would be:

public async Task DownloadFileAsync()
{
    using(var client = new WebClient())
    {
         await client.DownloadFileTaskAsync(
            new Uri("http://www.acromix.net16.net/download/test.exe"),
            "test.exe");
    }
}
Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59
0

Thanks for the answers...

Anyway, I found out that I can't really download an .exe file from where I hosted my website (000webhost) because it is blocked (for safety reasons I think).

A workaround, first, I need to put an .exe file to a zip folder then upload it so I would be able to download it successfully...

newbieguy
  • 658
  • 2
  • 11
  • 29