-1

My code looks like this:

    private static WebClient wc = new WebClient;
...
wc.DownloadFileAsync(URL, FilePath);
wc.DownloadProgressChanged += (s, ev) =>
{
    //Do stuff
};
wc.DownloadFileCompleted += (s, ev) =>
{
    //All the rest of the code
};

However, as soon as DownloadFileAsync is executed, the program immediately closes leaving me with a 0KB file instead of the downloaded file (no error occurs). I believe that it just completely ignores DownloadProgressChanged and executes the code inside the brackets. I'm just assuming

  • You need to show more code of where DownloadFileAsync is called. Your program is likely ending before the download completes. Because this is a console application most likely you just need to change it to a normal `DownloadFile` and move the code in `DownloadFileCompleted` after the download file call. – Scott Chamberlain Jul 30 '17 at 18:10

1 Answers1

0

As Scott Chamberlain correctly states, your program seemingly ends before DownloadFileCompleted gets called. If this assumption is correct, wait in the main thread until then, like so:

var completed = new AutoResetEvent(false);
wc.DownloadFileAsync(URL, FilePath);
wc.DownloadProgressChanged += (s, ev) =>
{
    //Do stuff
};
wc.DownloadFileCompleted += (s, ev) =>
{
    //All the rest of the code
    completed.Set();
};
completed.WaitOne();
tinudu
  • 1,139
  • 1
  • 10
  • 20