Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 捕获特定的WebException(550)_C#_.net_Exception_Exception Handling_Http Status Codes - Fatal编程技术网

C# 捕获特定的WebException(550)

C# 捕获特定的WebException(550),c#,.net,exception,exception-handling,http-status-codes,C#,.net,Exception,Exception Handling,Http Status Codes,假设我创建并执行了一个System.Net.FtpWebRequest 我可以使用catch(WebException-ex){}捕获此请求引发的任何与web相关的异常。但是,如果由于未找到(550)文件而引发异常时,我只想执行一些逻辑,该怎么办 最好的方法是什么?我可以复制异常消息并测试是否相等: const string fileNotFoundExceptionMessage = "The remote server returned an error: (550) File un

假设我创建并执行了一个
System.Net.FtpWebRequest

我可以使用
catch(WebException-ex){}
捕获此请求引发的任何与web相关的异常。但是,如果由于未找到
(550)文件而引发异常时,我只想执行一些逻辑,该怎么办

最好的方法是什么?我可以复制异常消息并测试是否相等:

const string fileNotFoundExceptionMessage =
    "The remote server returned an error: (550) File unavailable (e.g., file not found, no access).";
if (ex.Message == fileNotFoundExceptionMessage) {
但从理论上讲,这一信息可能会随着时间的推移而改变

或者,我可以测试一下异常消息是否包含“550”。如果消息被更改,这种方法可能更有效(它可能仍然在文本的某个地方包含“550”)。当然,如果其他
WebException
的文本恰好包含“550”,那么这种测试也会返回true


似乎没有一种方法仅用于访问异常的编号。这可能吗?

WebException
公开一个可供检查的属性

如果需要实际的HTTP响应代码,可以执行以下操作:

(int)((HttpWebResponse)ex.Response).StatusCode

声明WebException对象,将捕获块中的ex值强制转换为该对象。然后您可以检查StatusCode属性。

以下是我最终使用的实际代码供参考:

catch (WebException ex) {
    if (ex.Status == WebExceptionStatus.ProtocolError &&
        ((FtpWebResponse)ex.Response).StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) {
        // Handle file not found here
    }

捕获一个
WebException
只会为您提供协议错误的
状态。您需要将ex.响应转换为HttpWebResponse,如上面的答案所示,以获得所需的代码(即404500)。