Capturing a specific WebException (550)

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

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

What is the best way to do this? I could copy the exception message and check for equality:

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

But theoretically it seems that this message may change along the way.

Or, I could just check to see if the error message "550". This approach will probably work if the message is modified (it will probably still contain "550" somewhere in the text). But, of course, such a test will also return true if the text for another WebException simply contains "550".

There seems to be no way to access only the number of exceptions. Is it possible?

+7
c # exception exception-handling
source share
3 answers

WebException provides a StatusCode property that you can check.

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

 (int)((HttpWebResponse)ex.Response).StatusCode 
+14
source share

For reference, here is 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
source share

Declare a WebException object by entering the ex value from your Catch block. Then you can check the StatusCode property.

-one
source share

All Articles