I've written a method to check if a directory already exists on an FTP server. The only way I could see to make this work was to return a different result from the method if an exception is thrown - very bad practice in my opinion. Is there a better way to write this?
public bool DirectoryExists(string directory)
{
if (String.IsNullOrEmpty(directory))
throw new ArgumentException("No directory was specified to check for");
// Ensure directory is ended with / to avoid false positives
if (!directory.EndsWith("/"))
directory += "/";
try
{
var request = (FtpWebRequest)WebRequest.Create(directory);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(Username, Password);
using (request.GetResponse())
{
return true;
}
}
catch (WebException)
{
return false;
}
}
The connection hostname, username and password referred to within this block of code are auto properties set when the class is initialized.