How to check if an FTP directory exists

前端 未结 10 1396
一个人的身影
一个人的身影 2020-12-01 10:26

Looking for the best way to check for a given directory via FTP.

Currently i have the following code:

private bool FtpDirectoryExists(string direct         


        
10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 11:15

    I was also stuck with a 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 an exception in case the directory didn't exist. This method didn't throw an exception.

    After a 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 the code is working for me.

    I think we should append forwardslash (/) to the URI of the ftp folder to get it to 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 (note the forwardslash at the end of the path):
    string ftpDirectory = "ftp://ftpserver.com/rootdir/test_if_exist_directory/";
    bool dirExists = DoesFtpDirectoryExist(ftpDirectory);
    

提交回复
热议问题