views:

1121

answers:

4

Hello Everyone,

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.

Thanks in advance, Billy

A: 

Navigate to the parent directory, execute the "ls" command, and parse the result.

Chris B. Behrens
Can i get an example?
Billy Logan
+1  A: 

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.

Tom Cabanski
A: 

Basically trapped the error that i receive when creating the directory like so.

private bool CreateFTPDirectory(string directory) {

    try
    {
        //create the directory
        FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(new Uri(directory));
        requestDir.Method = WebRequestMethods.Ftp.MakeDirectory;
        requestDir.Credentials = new NetworkCredential("username", "password");
        requestDir.UsePassive = true;
        requestDir.UseBinary = true;
        requestDir.KeepAlive = false;
        FtpWebResponse response = (FtpWebResponse)requestDir.GetResponse();
        Stream ftpStream = response.GetResponseStream();

        ftpStream.Close();
        response.Close();

        return true;
    }
    catch (WebException ex)
    {
        FtpWebResponse response = (FtpWebResponse)ex.Response;
        if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
        {
            response.Close();
            return true;
        }
        else
        {
            response.Close();
            return false;
        }  
    }
}
Billy Logan
A: 

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:

String directory = "ftp://some.domain.com/mydirectory"
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(new Uri(directory));

I found this gets turned into

"ftp:/some.domain.com/home/usr/fred/mydirectory"

to stop this change the directory Uri to:

String directory = "ftp://some.domain.com//mydirectory"

Then every this starts working.

Tony Lambert