c# - 正确处理两个 WebException

标签 c# exception webclient 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
        }
    }
}

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

最佳答案

基于 this MSDN article , 你可以按照以下几行做一些事情:

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 是什么是。

关于c# - 正确处理两个 WebException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2650758/

相关文章:

c# - 为什么通过 Process.Start() 调用时 "cmd.exe/C command"不会结束?

c# - 如何让我的 wpf 应用程序等待 3 分钟后再重新加载数据?

c# - 命名空间 'Documents' 中不存在类型或命名空间名称 'System.Windows'

wcf - 如何将WCF异常传达给WebClient

wcf - 在 WCF 服务中使用 WebClient

c# - 通过 REST API 删除短信和语音的 Twilio 演示 URL

Java - 应该在哪里以及如何使用异常?

c# - 新的 ASP.NET Core MVC 项目抛出异常

c++ - Boost.Coroutine 在 iPhone 上崩溃

c# - "A connection attempt failed because the connected party did not properly respond after a period of time"使用 WebClient