none
DownloadFail on WebClient RRS feed

  • Question

  • Hi everyone,

    I'm having a problem with downloading a file (in bad internet connection condition), basically this how the file appears:

    see, the file is created but contain no data, this cause errors in my project when I use this image file.

    try { 
         client.DownloadFileAsync(new Uri(Image1UrlString), path + "Image1.png"); }
    catch {
         MessageBox.Show("error."); // this does not work
         Application.Current.Shutdown();
    }

    on good internet condition, this works fine.
    but there is no exception if the file is not downloaded 100%, if it is, the application continues, if not, application shutdown.

    please help

    Sunday, February 4, 2018 4:15 PM

Answers

All replies

  • If you use the Async operation, the errors are only caught when the Async operation completes, not when you start it (which is what we see in the try...catch in your code).

    You can use client.DownloadFile instead of client.DownloadFileAsync.

    OR if you still want the Async operation, add a DownloadCompleted event handler:

    https://msdn.microsoft.com/en-us/library/system.net.webclient.downloadfilecompleted(v=vs.110).aspx

    The eventargs for the event handler will provide an "Error" property that you can examine to determine if the download failed.

    • Marked as answer by Zuher Laith Sunday, February 4, 2018 6:26 PM
    Sunday, February 4, 2018 5:12 PM
    Moderator
  • If you use the Async operation, the errors are only caught when the Async operation completes, not when you start it (which is what we see in the try...catch in your code).

    You can use client.DownloadFile instead of client.DownloadFileAsync.

    OR if you still want the Async operation, add a DownloadCompleted event handler:

    https://msdn.microsoft.com/en-us/library/system.net.webclient.downloadfilecompleted(v=vs.110).aspx

    The eventargs for the event handler will provide an "Error" property that you can examine to determine if the download failed.

    I believe you are right,
    Using DownloadFile method instead of DownloadFileAsync did the job for what I want.

    I wasn't sure that adding DownloadCompleted event handler could solve this out.

    but thanks for help!!
    Sunday, February 4, 2018 6:26 PM