How to catch 404 WebException for WebClient.DownloadFileAsync

10,897

Solution 1

You need to handle the DownloadFileCompleted event and check the Error property of the AsyncCompletedEventArgs.

There are good examples in the links.

Solution 2

You can try this code:

WebClient wcl;

void Test()
{
    Uri sUri = new Uri("http://google.com/unknown/folder");
    wcl = new WebClient();
    wcl.OpenReadCompleted += onOpenReadCompleted;
    wcl.OpenReadAsync(sUri);
}

void onOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    if (e.Error != null)
    {
        HttpStatusCode httpStatusCode = GetHttpStatusCode(e.Error);
        if (httpStatusCode == HttpStatusCode.NotFound)
        {
            // 404 found
        }
    }
    else if (!e.Cancelled)
    {
        // Downloaded OK
    }
}

HttpStatusCode GetHttpStatusCode(System.Exception err)
{
    if (err is WebException)
    {
        WebException we = (WebException)err;
        if (we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            return response.StatusCode;
        }
    }
    return 0;
}
Share:
10,897
Paul
Author by

Paul

It is just a website. Life is somewhere else. Answers to downvoted question won't be accepted. Period. My wishlist The right syntax of with in Delphi: with r := obj.MyRecord do begin r.Field1 := 1; r.Field2 := '2'; // ... end; Favorites https://stackoverflow.blog/2019/10/17/imho-the-mythical-fullstack-engineer/ http://www.catb.org/esr/faqs/smart-questions.html Stackoverflow How to reduce image size on Stack Overflow Unicode Is there a list of characters that look similar to English letters? Windows How to programmatically get DLL dependencies Device misdetected as serial mouse Catch MSVCR120 missing error message in Delphi Get members of COM object via Delphi Olevariant type Controlling the master speaker volume in Windows 7 Filename timestamp in Windows CMD batch script getting truncated https://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory Linux How to control backlight by terminal command MS Visual Studio How to change "Visual Studio 2017" folder location? Delphi Convert a null-delimited PWideChar to list of strings Out-of-the-box flat borderless button TFDConnection.OnRecover is never fired when PostgreSQL stops TScrollBox with customized flat border color and width? How to redirect mouse events to another control? Creating object instance based on unconstrained generic type how to create a TCustomControl that behaves like Tpanel? https://stackoverflow.com/a/43990453 - How to hack into a read-only direct getter property With DDevExtensions you can disable storing Explicit... properties in the dfm https://github.com/RomanYankovsky/DelphiAST C Arrow operator (->) usage in C The Definitive C++ Book Guide and List GDI+ How to rotate Text in GDI+? GDI+ performance tricks MSXML schema validation with msxml in delphi How can I get English error messages when loading XML using MSXML Inno Setup: Save XML document with indentation PostgreSQL Checking for existence of index in PostgreSQL Web Will the IE9 WebBrowser Control Support all of IE9's features, including SVG? http://howtocenterincss.com MVC for Web, MVP for Winforms and MVVM for WPF. Just an observation: Most of the claims such as "I can't understand what you wrote", "Please provide more details", etc. are made by people with a relatively low SO score. People with the highest score on SO understand everything. Template: This is an abandoned question. Author has no longer anything to do with the topic and can neither approve nor decline your answer.

Updated on June 18, 2022

Comments

  • Paul
    Paul almost 2 years

    This code:

    try
    {
      _wcl.DownloadFile(url, currentFileName);
    }
    catch (WebException ex)
    {
      if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
        if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)
          Console.WriteLine("\r{0} not found.     ", currentFileName);
    }
    

    downloads file and informs if 404 error occured.

    I decided to download files asynchronously:

    try
    {
      _wcl.DownloadFileAsync(new Uri(url), currentFileName);
    }
    catch (WebException ex)
    {
      if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
        if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)
          Console.WriteLine("\r{0} not found.     ", currentFileName);
    }
    

    Now this catch block does not fire if server returns a 404 error and WebClient produces an empty file.

  • Paul
    Paul almost 11 years
    and delete an empty file every time?
  • Jim Mischel
    Jim Mischel almost 11 years
    @Paul: Yes, if there was an error. DownloadFileAsync apparently opens a file to prepare for writing. It closes the file when done, error or no. If you don't want the file, delete it.