正确处理两个WebException

bar*_*ron 18 c# webclient exception-handling downloadfile webexception

我正在努力处理两种不同WebException的问题.

基本上他们在打电话后处理 WebClient.DownloadFile(string address, string fileName)

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

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

可能会有更多,但这是我迄今为止发现最重要的内容.

那么我应该如何处理这个问题,因为它们都是,WebException但我想以不同的方式处理每个案例.

这是我到目前为止:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Zac*_*son 27

根据这篇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
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定这WebExceptionStatus.NameResolutionFailure是您看到的错误,但您可以检查抛出的异常并确定WebExceptionStatus该错误的内容.