正确处理两个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。 我会假设有更好或更精确的方法来做到这一点?

谢谢

根据这篇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是您看到的错误,但您可以检查抛出的exception并确定该错误的WebExceptionStatus是什么。