问题描述
我正在尝试处理两个不同的 WebException
。
基本上,它们在调用 WebClient.DownloadFile(string address,string fileName)
$ b
AFAIK,到目前为止,我有两个我必须处理,两个 WebException
的:
- 远程名称无法解析(即,没有网络连接访问服务器以下载文件)
- (404)文件不包含(即文件不存在于服务器上)
可能有更多,但这是迄今为止我发现最重要的。 / p>
所以我应该如何正确地处理这个问题,因为它们都是 WebException
,但我想处理上述每个案例
这是我迄今为止所做的:
try
{
using(var client = new WebClient())
{
client.DownloadFile(...);
}
}
catch(InvalidOperationException ioEx)
{
if(ioEx是WebException)
{
if(ioEx.Message.Contains (404)
{
// handle 404
}
if(ioEx.Message.Contains(remote name can not)
{
//句柄文件不存在
}
}
}
正如你所看到的那样,我正在检查消息以查看它是什么类型的WebException,我会假设有更好或更准确的方法来实现?
谢谢
根据,你可以按照以下几点做一些事情:
try
{
//尝试在这里下载文件
}
catch(WebException ex)
{
if( ex.Status == WebExceptionStatus.ProtocolError )
{
if(((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
//处理404这里
}
}
else if(ex.Status == WebExceptionStatus.NameResolutionFailure)
{
//句柄名称解析失败
}
}
我不确定 WebExceptionStatus.NameResolutionFailure
是您的错误看到,但您可以检查抛出的异常,并确定该错误的 WebExceptionStatus
。
I am trying to handle two different WebException
's properly.
Basically they are handled after calling WebClient.DownloadFile(string address, string fileName)
AFAIK, so far there are two I have to handle, both WebException
's:
- The remote name could not be resolved (i.e. No network connectivity to access server to download file)
- (404) File not nound (i.e. the file doesn't exist on the server)
There may be more but this is what I've found most important so far.
So how should I handle this properly, as they are both WebException
's but I want to handle each case above differently.
This is what I have so far:
try
{
using (var client = new WebClient())
{
client.DownloadFile("...");
}
}
catch(InvalidOperationException ioEx)
{
if (ioEx is WebException)
{
if (ioEx.Message.Contains("404")
{
//handle 404
}
if (ioEx.Message.Contains("remote name could not")
{
//handle file doesn't exist
}
}
}
As you can see I am checking the message to see what type of WebException it is. I would assume there is a better or a more precise way to do this?
Thanks
Based on this MSDN article, you could do something along the following lines:
try
{
// try to download file here
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
// handle the 404 here
}
}
else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
{
// handle name resolution failure
}
}
I'm not certain that WebExceptionStatus.NameResolutionFailure
is the error you are seeing, but you can examine the exception that is thrown and determine what the WebExceptionStatus
for that error is.
这篇关于处理两个WebException的正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!