如何检查 WebClient 请求是否存在 404 错误 [英] How do I check a WebClient Request for a 404 error

查看:33
本文介绍了如何检查 WebClient 请求是否存在 404 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个下载到文件的程序.第二个文件不是必需的,只包含了一些时间.如果不包含第二个文件,它将返回 HTTP 404 错误.

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.

现在,问题是当返回这个错误时,它会结束整个程序.我想要的是继续程序并忽略HTTP错误.所以,我的问题是如何从 WebClient.DownloadFile 请求中捕获 HTTP 404 错误?

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

推荐答案

在代码中使用 try catch WebException 并检查 Exception消息 - 它将包含 http StatusCode.

Use a try catch WebException in your code and examine the Exception message - it will contain the http StatusCode.

您可以清除Exception并继续.

这篇关于如何检查 WebClient 请求是否存在 404 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆