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; }
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.
WebClient will throw a WebException for all 4xx and 5xx responses.
try { downloader.DownloadFile(videoAddress, videoPath); } catch (WebException ex) { // handle it here }
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With