2

I have the following code in my method:

// make the FTP request
var request = (FtpWebRequest)WebRequest.Create(serverUri);
request.KeepAlive = true;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
return (FtpWebResponse)request.GetResponse();

The serverUri is valid and this works if the directory does not exist already on the server. However, if the directory does already exist a System.Net.WebException : The remote server returned an error: (550) File unavailable (e.g., file not found, no access) occurs.

Why does this exception occur when I call request.GetResponse() instead of setting the FtpWebResponse object's StatusCode to FtpStatusCode.ActionNotTakenFileUnavailable which is 550?

I find information on how to handle the exception and get the status code and description from it. But I would like to know why the exception is thrown in the first place instead of setting the response object's status code and letting the coder decide if it warrants an exception.

kero
  • 10,647
  • 5
  • 41
  • 51
NathanDykstra
  • 85
  • 1
  • 11

2 Answers2

0

This is actually behaving as designed. You'll need to catch that specific exception and then interrogate the response. Per the MSDN documentation:

If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.

So, the code might look like this:

try
{
    return (FtpWebResponse)request.GetResponse();
}
catch (WebException we)
{
    // interrogate the WebException for the response data you're looking for 
}
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
0

Because getting an error code after making an Http request matches perfectly with the Exception semantics of the language. You don't actually have a meaningful response to get back and since it is an "exceptional" case it makes sense to translate the web error to a WebException.

atomaras
  • 2,468
  • 2
  • 19
  • 28