How to check if an FTP directory exists

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

    I assume that you are already somewhat familiar with FtpWebRequest, as this is the usual way to access FTP in .NET.

    You can attempt to list the directory and check for an error StatusCode.

    try 
    {  
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.microsoft.com/12345");  
        request.Method = WebRequestMethods.Ftp.ListDirectory;  
        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())  
        {  
            // Okay.  
        }  
    }  
    catch (WebException ex)  
    {  
        if (ex.Response != null)  
        {  
            FtpWebResponse response = (FtpWebResponse)ex.Response;  
            if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)  
            {  
                // Directory not found.  
            }  
        }  
    } 
    

提交回复
热议问题