Looking for the best way to check for a given directory via FTP.
Currently i have the following code:
private bool FtpDirectoryExists(string directory, string username, string password)
{
try
{
var request = (FtpWebRequest)WebRequest.Create(directory);
request.Credentials = new NetworkCredential(username, password);
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
return false;
else
return true;
}
return true;
}
This returns false whether the directory is there or not. Can someone point me in the right direction.
I would try something along this lines:
Send MLST <directory> FTP command (defined in RFC3659) and parse it's output. It should return valid line with directory details for existing directories.
If MLST command is not available, try changing the working directory into the tested directory using a CWD command. Don't forget to determine the current path (PWD command) prior to changing to a tested directory to be able to go back.
On some servers combination of MDTM and SIZE command can be used for similar purpose, but the behavior is quite complex and out of scope of this post.
This is basically what DirectoryExists method in the current version of our Rebex FTP component does. The following code shows how to use it:
Basically trapped the error that i receive when creating the directory like so.
I tried every which way to get a solid check but neither the
WebRequestMethods.Ftp.PrintWorkingDirectory
norWebRequestMethods.Ftp.ListDirectory
methods would work correctly. They failed when checking forftp://<website>/Logs
which doesnt exist on the server but they say it does.So the method I came up with was to try to upload to the folder. However, one 'gotcha' is the path format which you can read about in this thread Uploading to Linux
Here is a code snippet
I couldn't get this @BillyLogans suggestion to work....
I found the problem was the default FTP directory was /home/usr/fred
When I used:
I found this gets turned into
to stop this change the directory Uri to:
Then this starts working.
For what it is worth, You'll make your FTP life quite a bit easier if you use EnterpriseDT's FTP component. It's free and will save you headaches because it deals with the commands and responses. You just work with a nice, simple object.
I was also stuck with the similar problem. I was using,
and waited for exception in case the directory doesn't exist. This method didn't throw exception.
After few hit and trials, I changed the directory from: "ftp://ftpserver.com/rootdir/test_if_exist_directory" to : "ftp://ftpserver.com/rootdir/test_if_exist_directory/". Now this piece is working for me.
I think we should append backslash (/) in the uri of the ftp folder to get this work.
As requested, the complete solution will now be: