FTP ListDirectory command returns status code 125
I have a bit of code that is supposed to check whether a directory exists on a remote server. It executes the ListDirectory
command on the path and expects a response if it exists and an exception if it doesn't.
The problem is that the command returns the code 125 DataAlreadyOpen
, so my code interprets that as success, when it should have failed.
I might be completely misunderstanding how FTP works. I'm creating开发者_如何学Python a new request every time, so I don't understand how a connection can already be open.
Oh, and the code works with root directories like ftp://myIP/Folder1
, but doesn't work with ftp://myIP/Folder1/Folder2
. I'm using the IIS FTP server, by the way.
public static bool DirectoryExists(string path)
{
try
{
var request = (FtpWebRequest)WebRequest.Create(path);
request.Credentials = new NetworkCredential("foo", "bar");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.KeepAlive = false;
using (var response = (FtpWebResponse)request.GetResponse())
return true;
}
catch (Exception ex)
{
return false;
}
}
How can I reliably check whether a directory exists? All the code examples I've found use this technique.
Try changing the request.Method to
request.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
I worked around this issue by using the WebRequestMethods.Ftp.MakeDirectory
command whenever I want to check if a directory exists. If it doesn't exist, it's created, if it exists, I catch the exception and carry on.
精彩评论