6

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
  • 25,812
  • 38
  • 124
  • 247

2 Answers2

6

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

There are good examples in the links.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • 1
    and delete an empty file every time? – Paul May 05 '13 at 19:12
  • @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. – Jim Mischel May 05 '13 at 19:17
4

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;
}
Sergey
  • 1,552
  • 20
  • 18