Search code examples
c#ftpsystem.net.webexception

.NET throws WebException instead of setting StatusCode


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.


Solution

  • 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.