How do I check a WebClient Request for a 404 error
you can try this code to get HTTP status code from WebException or OpenReadCompletedEventArgs.Error:
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;
}
WebClient will throw a WebException for all 4xx and 5xx responses.
try {
downloader.DownloadFile(videoAddress, videoPath);
}
catch (WebException ex) {
// handle it here
}
Put the try
catch
inside your foreach
Loop.
foreach (string[] i in textList)
{
try
{
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;
if(Download(videoAddress, videoPath) == false)
{
//Download failed. Do what you want to do.
}
textBox1.Text = textBox1.Text + @"Complete video for" + videoName;
if(Download(imgAddress, imgPath)== false)
{
//Download failed. Do what you want to do.
}
textBox1.Text = textBox1.Text + @"Complete img for" + videoName;
}
catch(Exception ex)
{
//Error like IO Exceptions, Security Errors can be handle here. You can log it if you want.
}
}
Private function to Download file
private bool Download(string url, string destination)
{
try
{
WebClient downloader = new WebClient();
downloader.DownloadFile(url, destination);
return true;
}
catch(WebException webEx)
{
//Check (HttpWebResponse)webEx.Response).StatusCode
// Or
//Check for webEx.Status
}
return false;
}
You can check the WebException
for status. Depending upon the error code you can continue or break.
Read More @ MSDN
- WebClient
- WebException.Status
- WebExceptionStatus
Suggestion
- Use Path.Combine to create folder path.
- Can use String.Format to join two strings, instead of
+
.
Hope this works for you.
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
}
}