Check if directory exists on FTP server
Asked Answered
C

1

10

I'm running a check to see if a directory exists on my FTP server:

    public bool DirectoryExists(string directory)
    {
        bool directoryExists;

        var request = (FtpWebRequest)WebRequest.Create(directory);
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        request.Credentials = new NetworkCredential("user", "pass");

        try
        {
            using (request.GetResponse())
            {
                directoryExists = true;
            }
        }
        catch (WebException)
        {
            directoryExists = false;
        }

        return directoryExists;
    }

In this case:

directory = @"ftp://ftp.example.com/Rubicon";

On my server, I have a folder named Rubicon1. This is causing my check to return true. How can I ensure that it fails unless it matches the directory name exactly?

Cambric answered 31/1, 2013 at 22:1 Comment(7)
can you get an list of directories in the parent? maybe it's hiddenSagittarius
See this: #266453 The reasoning applies to any volatile resource, which definitely includes FTP shares.Coauthor
@Sagittarius the line where it says Create is for creating the FTP web request, not the actual FTP DirectoryRecondition
just tried this with an FTP of mine and it works as expected. Could it be their fault again? :)Recondition
@w0lf, thanks i knew that, but phrased my statement terribly.Sagittarius
@w0lf: I've asked my web server provider to look into it, but they switched FTP services because of the last issue and are certain that everything is working as intended. Personally, I've tried several different directory names, and if ANY of them contain Rubicon, the check passes.Cambric
Try to send WebRequestMethods.Ftp.MakeDirectory for the desired path. If the response face failure, it'll return a 550 error about accessing or finding the relative file/folder.Manville
C
6

I successfully solved this issue by changing my directory to be:

directory = @"ftp://ftp.example.com/Rubicon/";
Cambric answered 1/2, 2013 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.