I wrote the following code a long time ago to determine if an FTP directory exists:
public bool DirectoryExists(string directory)
{
try
{
FtpWebRequest request = GetRequest(directory);
request.Method = WebRequestMethods.Ftp.ListDirectory;
using (FtpWebResponse response = request.GetResponse() as FtpWebResponse)
{
StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII);
sr.ReadToEnd();
sr.Close();
response.Close();
}
return true;
}
catch { }
return false;
}
protected FtpWebRequest GetRequest(string filename = "")
{
FtpWebRequest request = WebRequest.Create(_host.GetUrl(filename)) as FtpWebRequest;
request.Credentials = new NetworkCredential(Username, Password);
request.Proxy = null;
request.KeepAlive = false;
return request;
}
This code has worked for several years, but today it doesn't. When testing a directory that does not exist, the code in DirectoryExists()
no longer throws an exception, and the method incorrectly returns true
.
If I assign the results of sr.ReadToEnd()
to a string, it is an empty string.
In this case, the code _host.GetUrl(filename)
returned "ftp://www.mydomain.com/Articles/winforms/accessing-the-windows-registry". This is the expected value. And still my DirectoryExists() method does not throw an exception when this path does not exist on the server. I even passed this non-existing directory to a method that uses WebRequestMethods.Ftp.ListDirectoryDetails
to build a directory listing. This method simply returns an empty listing and also throws no exception.
I believe I first encountered this issue when I moved my code to a new computer with Visual Studio 2013. I'm using .NET 4.5 and got the same behavior when using .NET 4.5.1.
Questions:
Why doesn't this code, which has worked for years and uses the same technique used on most of the online examples I found, work? And what could possibly cause this code to suddenly stop working?
Is there a way to detect for the presence of a directory that works? I suppose the other approach is to scan the parent directory, although the logic would need to be different when the routine is supposed to verify the root directory.