How to check if an FTP directory exists

前端 未结 10 1404
一个人的身影
一个人的身影 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:14

    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:///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; 
    } 
    

提交回复
热议问题