我试图处理两个不同的 WebException's正常。

基本上他们是处理后叫 WebClient.DownloadFile(string address, string fileName)

据我所知,迄今为止,有两个我来处理,既 WebException's:

  • 远程名称不可能得到解决(即没有网络连接到访问服务器下载的文件)
  • (404)文件不nound(即该文件不存在服务器上的)

可能有更多,但这是我发现了什么最重要的为止。

所以我应该怎么处理这一点正确,因为他们都是 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。我会假设有一个更好的或更精确的方式做到这一点?

感谢

有帮助吗?

解决方案

基于上 这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 对于这一错误。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top