How do I check a WebClient Request for a 404 error

Alex Gatti picture Alex Gatti · Jan 23, 2012 · Viewed 40k times · Source

I have a program I'm writing that downloads to files. The second file is not neccassary and is only some times included. When the second file is not included it will return an HTTP 404 error.

Now, the problem is that when this error is returned it ends the whole program. What I want is to continue the program and ignore the HTTP error. So, my question is how do I catch an HTTP 404 error from a WebClient.DownloadFile request?

This is the code currently used::

WebClient downloader = new WebClient();
foreach (string[] i in textList)
{
    String[] fileInfo = i;
    string videoName = fileInfo[0];
    string videoDesc = fileInfo[1];
    string videoAddress = fileInfo[2];
    string imgAddress = fileInfo[3];
    string source = fileInfo[5];
    string folder = folderBuilder(path, videoName);
    string infoFile = folder + '\\' + removeFileType(retrieveFileName(videoAddress)) + @".txt";
    string videoPath = folder + '\\' + retrieveFileName(videoAddress);
    string imgPath = folder + '\\' + retrieveFileName(imgAddress);
    System.IO.Directory.CreateDirectory(folder);
    buildInfo(videoName, videoDesc, source, infoFile);
    textBox1.Text = textBox1.Text + @"begining download of files for" + videoName;
    downloader.DownloadFile(videoAddress, videoPath);
    textBox1.Text = textBox1.Text + @"Complete video for" + videoName;
    downloader.DownloadFile(imgAddress, imgPath);
    textBox1.Text = textBox1.Text + @"Complete img for" + videoName;
}

Answer

Ian Kemp picture Ian Kemp · Dec 7, 2013

If you specifically want to catch error 404:

using (var client = new WebClient())
{
  try
  {
    client.DownloadFile(url, destination);
  }
  catch (WebException wex)
  {
    if (((HttpWebResponse) wex.Response).StatusCode == HttpStatusCode.NotFound)
    {
      // error 404, do what you need to do
    }
  }
}