How to check if an FTP Directory Exists

2019-01-11 06:41发布

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.

10条回答
Root(大扎)
2楼-- · 2019-01-11 06:43

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:

string path = "/path/to/directory";

Rebex.Net.Ftp ftp = new Rebex.Net.Ftp();
ftp.Connect("hostname");
ftp.Login("username","password");

Console.WriteLine(
  "Directory '{0}' exists: {1}", 
  path, 
  ftp.DirectoryExists(path)
);

ftp.Disconnect();
查看更多
forever°为你锁心
3楼-- · 2019-01-11 06:47

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;
        }  
    }
}
查看更多
smile是对你的礼貌
4楼-- · 2019-01-11 06:49

I tried every which way to get a solid check but neither the WebRequestMethods.Ftp.PrintWorkingDirectory nor WebRequestMethods.Ftp.ListDirectory methods would work correctly. They failed when checking for ftp://<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

private bool DirectoryExists(string d) 
{ 
    bool exists = true; 
    try 
    { 
        string file = "directoryexists.test"; 
        string path = url + homepath + d + "/" + file;
        //eg ftp://website//home/directory1/directoryexists.test
        //Note the double space before the home is not a mistake

        //Try to save to the directory 
        req = (FtpWebRequest)WebRequest.Create(path); 
        req.ConnectionGroupName = "conngroup1"; 
        req.Method = WebRequestMethods.Ftp.UploadFile; 
        if (nc != null) req.Credentials = nc; 
        if (cbSSL.Checked) req.EnableSsl = true; 
        req.Timeout = 10000; 

        byte[] fileContents = System.Text.Encoding.Unicode.GetBytes("SAFE TO DELETE"); 
        req.ContentLength = fileContents.Length; 

        Stream s = req.GetRequestStream(); 
        s.Write(fileContents, 0, fileContents.Length); 
        s.Close(); 

        //Delete file if successful 
        req = (FtpWebRequest)WebRequest.Create(path); 
        req.ConnectionGroupName = "conngroup1"; 
        req.Method = WebRequestMethods.Ftp.DeleteFile; 
        if (nc != null) req.Credentials = nc; 
        if (cbSSL.Checked) req.EnableSsl = true; 
        req.Timeout = 10000; 

        res = (FtpWebResponse)req.GetResponse(); 
        res.Close(); 
    } 
    catch (WebException ex) 
    { 
        exists = false; 
    } 
    return exists; 
} 
查看更多
叼着烟拽天下
5楼-- · 2019-01-11 06:49

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 this starts working.

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-11 06:52

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.

查看更多
混吃等死
7楼-- · 2019-01-11 07:04

I was also stuck with the similar problem. I was using,

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftpserver.com/rootdir/test_if_exist_directory");  
request.Method = WebRequestMethods.Ftp.ListDirectory;  
FtpWebResponse response = (FtpWebResponse)request.GetResponse();

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:

public bool DoesFtpDirectoryExist(string dirPath)
{
    try
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(dirPath);  
        request.Method = WebRequestMethods.Ftp.ListDirectory;  
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        return true;
     }
     catch(WebException ex)
     {
         return false;
     }
}

//Calling the method:
string ftpDirectory = "ftp://ftpserver.com/rootdir/test_if_exist_directory/"; //Note: backslash at the last position of the path.
bool dirExists = DoesFtpDirectoryExist(ftpDirectory);
查看更多
登录 后发表回答