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?

jdphenix
  • 15,022
  • 3
  • 41
  • 74
PiousVenom
  • 6,888
  • 11
  • 47
  • 86
  • 1
    can you get an list of directories in the parent? maybe it's hidden – ericosg Jan 31 '13 at 22:05
  • See this: http://stackoverflow.com/questions/265953/how-can-you-easily-check-if-access-is-denied-for-a-file-in-net/265958#265958 The reasoning applies to any volatile resource, which definitely includes FTP shares. – Joel Coehoorn Jan 31 '13 at 22:06
  • @ericosg the line where it says `Create` is for creating the FTP web request, not the actual FTP Directory – Cristian Lupascu Jan 31 '13 at 22:06
  • 2
    just tried this with an FTP of mine and it works as expected. Could it be [their fault](http://stackoverflow.com/a/14635728/390819) again? :) – Cristian Lupascu Jan 31 '13 at 22:08
  • @w0lf, thanks i knew that, but phrased my statement terribly. – ericosg Jan 31 '13 at 22:09
  • @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. – PiousVenom Jan 31 '13 at 23:04
  • 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. – MahanGM Jan 31 '13 at 23:08

1 Answers1

6

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

directory = @"ftp://ftp.example.com/Rubicon/";
jdphenix
  • 15,022
  • 3
  • 41
  • 74
PiousVenom
  • 6,888
  • 11
  • 47
  • 86