Catching a specific WebException (550)

谁说胖子不能爱 提交于 2019-12-12 08:46:39

问题


Let's say I create and execute a System.Net.FtpWebRequest.

I can use catch (WebException ex) {} to catch any web-related exception thrown by this request. But what if I have some logic that I only want to execute when the exception is thrown due to (550) file not found?

What's the best way to do this? I could copy the exception message and test for equality:

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

But theoretically it seems like this message could change down the road.

Or, I could just test to see if the exception message contains "550". This approach is probably more likely to work if the message is changed (it will likely still contain "550" somewhere in the text). But of course such a test would also return true if the text for some other WebException just happens to contain "550".

There doesn't seem to be a method for accessing just the number of the exception. Is this possible?


回答1:


WebException exposes a StatusCode property that you can check.

If you want the actual HTTP response code you can do something like this:

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



回答2:


For reference, here's the actual code I ended up using:

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



回答3:


Declare a WebException object, casting the ex value from your Catch block to it. Then you can check the StatusCode Property.



来源:https://stackoverflow.com/questions/674726/catching-a-specific-webexception-550

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!