Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check a WebClient Request for a 404 error

Tags:

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; } 
like image 249
Alex Gatti Avatar asked Jan 23 '12 08:01

Alex Gatti


People also ask

How do I fix Error 404 on my tablet?

Clear your browser cache: If you think the 404 error is only happening to you (for instance, you can load it on another device), try clearing the browser's cache. Check out our guide on clearing your cache in all popular browsers. Change DNS servers: Changing your DNS server can occasionally fix the 404 error.


2 Answers

WebClient will throw a WebException for all 4xx and 5xx responses.

try {     downloader.DownloadFile(videoAddress, videoPath); } catch (WebException ex) {     // handle it here } 
like image 23
John Sheehan Avatar answered Sep 22 '22 02:09

John Sheehan


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     }   } } 

Or, using C# 7 or later:

using (var client = new WebClient()) {   try   {     client.DownloadFile(url, destination);   }   catch (WebException ex) when         (ex.Response is HttpWebResponse wr && wr.StatusCode == HttpStatusCode.NotFound)   {           // error 404, do what you need to do   } } 
like image 104
Ian Kemp Avatar answered Sep 24 '22 02:09

Ian Kemp