C# 如何检查 WebClient 请求是否存在 404 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8968641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check a WebClient Request for a 404 error
提问by Alex Gatti
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 404error.
我正在编写一个下载到文件的程序。第二个文件不是必需的,只包含了一些时间。当不包含第二个文件时,它将返回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 404error from a WebClient.DownloadFilerequest?
现在,问题是当返回此错误时,它会结束整个程序。我想要的是继续程序并忽略HTTP错误。所以,我的问题是如何HTTP 404从WebClient.DownloadFile请求中捕获错误?
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;
}
采纳答案by Laird Streak
Use a try catchWebExceptionin your code and examine the Exceptionmessage - it will contain the http StatusCode.
try catchWebException在您的代码中使用 a并检查Exception消息 - 它将包含 http StatusCode。
You can clear the Exceptionand continue.
您可以清除Exception并继续。
回答by Amar Palsapure
Put the trycatchinside your foreachLoop.
把trycatch你的foreach循环里面。
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 WebExceptionfor status. Depending upon the error code you can continue or break.
您可以检查WebException状态。根据错误代码,您可以继续或中断。
Read More @ MSDN
阅读更多@ MSDN
Suggestion
建议
- Use Path.Combineto create folder path.
- Can use String.Formatto join two strings, instead of
+.
- 使用Path.Combine创建文件夹路径。
- 可以使用String.Format来连接两个字符串,而不是
+.
Hope this works for you.
希望这对你有用。
回答by John Sheehan
WebClient will throw a WebExceptionfor all 4xx and 5xx responses.
WebClient 将为所有 4xx 和 5xx 响应抛出一个 WebException。
try {
downloader.DownloadFile(videoAddress, videoPath);
}
catch (WebException ex) {
// handle it here
}
回答by Guillaume Slashy
Use a try{} catch{} block with the WebException inside your loop ! Dunno what IDE u are using but with Visual Studio u can get a lot of information about the exception :)
在循环中使用带有 WebException 的 try{} catch{} 块!不知道你在使用什么 IDE,但使用 Visual Studio 你可以获得很多关于异常的信息:)
回答by Holger
As other write, as try-catch would suffice.
正如其他人所写,因为 try-catch 就足够了。
Another tip is to use HTTP HEADto check if there is anything there (it's lighter than doing a full HTTP GET):
另一个技巧是使用HTTP HEAD检查那里是否有任何东西(它比执行完整的 HTTP GET 更轻):
var url = "url to check;
var req = HttpWebRequest.Create(url);
req.Method = "HEAD"; //this is what makes it a "HEAD" request
WebResponse res = null;
try
{
res = req.GetResponse();
res.Close();
return true;
}
catch
{
return false;
}
finally
{
if (res != null)
res.Close();
}
回答by Ian Kemp
If you specificallywant to catch error 404:
如果您特别想捕获错误 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
}
}
}
回答by Sergey
you can try this code to get HTTP status code from WebException or OpenReadCompletedEventArgs.Error:
您可以尝试使用此代码从 WebException 或 OpenReadCompletedEventArgs.Error 获取 HTTP 状态代码:
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;
}
回答by Simon_Weaver
Important: On a 404 failure DownloadFileTaskAsyncwill throw an exception but will ALSO create an empty file. This can be confusing to say the least!
重要提示:在 404 失败时DownloadFileTaskAsync会抛出异常,但也会创建一个空文件。至少可以说这可能令人困惑!
Took me way too long to realize that this code creates an empty file in addition to throwing an exception:
我花了很长时间才意识到除了抛出异常之外,这段代码还创建了一个空文件:
await webClient.DownloadFileTaskAsync(new Uri("http://example.com/fake.jpg"), filename);
Instead I switched to this (DownloadDataTaskAsyncinstead of File):
相反,我切换到这个(DownloadDataTaskAsync而不是File):
var data = await webClient.DownloadDataTaskAsync(new Uri("http://example.com/fake.jpg"));
File.WriteAllBytes(filename, data);
*I'm not sure about 500 behavior, but for sure a 404 does this.
*我不确定 500 的行为,但可以肯定的是 404 会这样做。

