C# Check if FTP Directory EXISTS

15,682

Solution 1

I got a work around for this problem. Not the best looking but it works.

Maybe this can help others with the same problem as mine.

public bool directoryExists2(string directory, string mainDirectory)
        {
            try
            {
                var list = this.GetFileList(mainDirectory);
                if (list.Contains(directory))
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

EDIT: I included the GetFileList method in response to Ray Chang's comment

public string[] GetFileList(string path)
        {
            var ftpPath = host + "/" + path;
            var ftpUser = user;
            var ftpPass = pass;
            var result = new StringBuilder();
            try
            {
                var strLink = ftpPath;
                var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(strLink));
                reqFtp.UseBinary = true;
                reqFtp.Credentials = new NetworkCredential(ftpUser, ftpPass);
                reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFtp.Proxy = null;
                reqFtp.KeepAlive = false;
                reqFtp.UsePassive = true;
                using (var response = reqFtp.GetResponse())
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        var line = reader.ReadLine();
                        while (line != null)
                        {
                            result.Append(line);
                            result.Append("\n");
                            line = reader.ReadLine();
                        }
                        result.Remove(result.ToString().LastIndexOf('\n'), 1);
                    }
                }
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                Console.WriteLine("FTP ERROR: ", ex.Message);
                return null;
            }

            finally
            {
                ftpRequest = null;
            }
        }

Solution 2

Try this:

public bool directoryExists(string directory)
{
    /* Create an FTP Request */
    ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
    /* Log in to the FTP Server with the User Name and Password Provided */
    ftpRequest.Credentials = new NetworkCredential(user, pass);
    /* Specify the Type of FTP Request */
    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    try
    {
        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        {
            return true;
        }
    }
    catch (Exception ex)
    {
        return false;
    }

            /* Resource Cleanup */
    finally
    {
        ftpRequest = null;
    }
}

Take note of this line using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())

Share:
15,682
finnTheHumin
Author by

finnTheHumin

Homies help homies, always. :')

Updated on June 15, 2022

Comments

  • finnTheHumin
    finnTheHumin almost 2 years

    I have this FTP Method that checks if a directory exists. It works fine at the start, but now, it's still returning true even if the directory does not exists. I tried many things, and set breakpoint to see what property of the response object I can use to determine whether the directory exists or not. I also searched the internet and the solutions don't seem to work for me. Here is my FTP method.

    public bool directoryExists(string directory)
                {
                    /* Create an FTP Request */
                    ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
                    /* Log in to the FTP Server with the User Name and Password Provided */
                    ftpRequest.Credentials = new NetworkCredential(user, pass);
                    /* Specify the Type of FTP Request */
                    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                    try
                    {
                        using (ftpRequest.GetResponse())
                        {
                            return true;
                        }
                        //var response = ftpRequest.GetResponse();
                        //if (response != null)
                        //    return true;
                        //else return false;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                        return false;
                    }
    
                    /* Resource Cleanup */
                    finally
                    {
                        ftpRequest = null;
                    }
                }
    

    And here is the method that calls it and returns true even if the directory does not exist:

    private string getDirectory(ref FtpClass ftp, string internalID)
            {
                string remoteSubPathDel = internalID + "\\trunk\\prod\\xml\\delete";
                string remoteSubPathUpdate = internalID + "\\trunk\\prod\\xml\\update";
                string remoteSubPathNew = internalID + "\\trunk\\prod\\xml\\new";
                if (ftp.directoryExists(remoteSubPathDel))
                    return remoteSubPathDel;
                else if (ftp.directoryExists(remoteSubPathUpdate))
                    return remoteSubPathUpdate;
                else if (ftp.directoryExists(remoteSubPathNew))
                    return remoteSubPathNew;
                else
                    return String.Empty;
            }
    

    Hope someone can help. Thanks! :)

  • mason
    mason almost 11 years
    Using exceptions is generally not a good way of handling things that you expect to happen. Slows down the code. It might be better to start at the root of the FTP server and perform a series of ListDirectory methods until you confirm that the directory you want exists.
  • Jonathan Wood
    Jonathan Wood about 10 years
    @mason: You think potentially searching the entire directory tree is faster than using an exception for this? I don't think so. If FtpWebRequest has a DirectoryExists() method, then that would be great. Otherwise, I think an exception is the logical approach.
  • Jonathan Wood
    Jonathan Wood about 10 years
    I used a similar approach in my tests for a directory's existence. However, today that code doesn't work. It fails to throw an exception when the directory does not exist. I've upgraded to VS2013. Trying to determine if some behavior has changed within .NET.
  • mason
    mason about 10 years
    @JonathanWood Exceptions are for things that you don't expect to happen and require special handling. They should not be used for something that can be regularly expected to happen. See Best Practices for Exceptions on MSDN. In a method that checks to see if a directory exists, I would think that it's reasonable to expect the directory not to exist fairly often.
  • Ray Cheng
    Ray Cheng about 9 years
    where is your this.GetFileList method code? and what is this?
  • finnTheHumin
    finnTheHumin about 9 years
    @RayCheng please see edit above. this refers to FTPClass.cs, which is a class I created for FTP Operations.
  • MiguelSlv
    MiguelSlv over 5 years
    i found out that some FTP servers need the path to end with "/", otherwise the path will considered to be a file path and will apply directory listening a level up.