捕获特定的WebException(550)

Law*_*ton 7 .net c# exception-handling exception http-status-codes

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

我可以catch (WebException ex) {}用来捕获此请求引发的任何与Web相关的异常.但是,如果我有一些逻辑,我只想在抛出异常时执行(550) file not found?

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

const string fileNotFoundExceptionMessage =
    "The remote server returned an error: (550) File unavailable (e.g., file not found, no access).";
if (ex.Message == fileNotFoundExceptionMessage) {
Run Code Online (Sandbox Code Playgroud)

但从理论上讲,这条消息似乎可能会改变.

或者,我可以测试一下异常消息是否包含"550".如果消息被更改,这种方法可能更有效(它可能在文本中的某处仍然包含"550").但是,如果其他一些文本WebException碰巧包含"550",那么这样的测试当然也会返回.

似乎没有一种方法可以只访问异常的数量.这可能吗?

And*_*are 14

WebException公开StatusCode您可以检查的财产.

如果你想要实际的HTTP响应代码,你可以这样做:

(int)((HttpWebResponse)ex.Response).StatusCode
Run Code Online (Sandbox Code Playgroud)