18

我正在尝试正确处理两个不同WebException的 '。

基本上他们在调用后处理WebClient.DownloadFile(string address, string fileName)

AFAIK,到目前为止,我必须处理两个,两个都是WebException

  • 无法解析远程名称(即没有网络连接到访问服务器下载文件)
  • (404) 文件不是名词(即文件在服务器上不存在)

可能还有更多,但这是我迄今为止发现的最重要的。

那么我应该如何正确处理这个问题,因为它们都是WebException's 但我想以不同的方式处理上述每种情况。

这是我到目前为止所拥有的:

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

如您所见,我正在检查消息以查看WebException它的类型。我会假设有更好或更精确的方法来做到这一点?

4

1 回答 1

29

根据这篇 MSDN 文章,您可以按照以下方式进行操作:

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

我不确定这WebExceptionStatus.NameResolutionFailure是您看到的错误,但您可以检查引发的异常并确定WebExceptionStatus该错误的原因。

于 2010-04-16T05:38:27.523 回答