【问题标题】:C# Check if FTP Directory EXISTSC# 检查 FTP 目录是否存在
【发布时间】:2013-05-19 14:15:09
【问题描述】:

我有这个 FTP 方法来检查目录是否存在。它在开始时工作正常,但现在,即使目录不存在,它仍然返回 true。我尝试了很多东西,并设置了断点来查看我可以使用响应对象的哪些属性来确定目录是否存在。我还搜索了互联网,解决方案似乎对我不起作用。这是我的 FTP 方法。

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

这是调用它的方法,即使目录不存在也返回true:

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

希望有人可以提供帮助。谢谢! :)

【问题讨论】:

  • 您将在使用 FTP 时遇到此问题。 FTP 服务器返回的信息未由 RFC 定义,因此某些客户端将无法解析响应。

标签: c# ftp directory exists


【解决方案1】:

In 2021 这适用于我们的 Linux 和 Windows live 从 ftp 服务器读取的框(在 Windows 和 Linux 上)

注意

  • Windows ftp 上的主文件夹是 web
  • Linux ftp 上的主文件夹是 public_html

TL;DR;

  • 底线:URL 需要以 / 结尾

有效:

ftp://ftp.yourdomain.com.br/public_html/
ftp://ftp.yourdomain.com.br//public_html/
ftp://ftp.yourdomain.com.br/web/
ftp://ftp.yourdomain.com.br//web/

它不起作用:

ftp://ftp.yourdomain.com.br/public_html
ftp://ftp.yourdomain.com.br//public_html
ftp://ftp.yourdomain.com.br/web
ftp://ftp.yourdomain.com.br//web

用法: //验证目录public_html是否存在

var url = "/public_html/";
var result = FtpUtil.DoesDirectoryExists(url,  "ftp://ftp.yourdomain.com.br", "ftp user here", "ftp password here");

static bool DoesDirectoryExists(string directory, string ftpHost, string ftpUser, string ftpPassword) {
                    FtpWebRequest ftpRequest = null;
                    try {
                            ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpHost + directory));
                            ftpRequest.Credentials = new NetworkCredential(ftpUser, string ftpPassword);
                            ftpRequest.UseBinary = true;// optional
                            ftpRequest.KeepAlive = false;// optional
                            ftpRequest.UsePassive = true;// optional
                            ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
        
                            using (FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse()) {
                                return true;//directory found
                            }
                    }
                    catch (WebException ex) {
                            if (ex.Response != null) {
                                FtpWebResponse response = (FtpWebResponse)ex.Response;
                                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                                    return false;// directory not found.  
                            }
                            return false; // directory not found.
                    }
                    finally {
                        ftpRequest = null;
                    }
        }

【讨论】:

    【解决方案2】:

    我解决了这个问题。不是最好看,但很管用。

    也许这可以帮助其他与我有同样问题的人。

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

    编辑:我包含了 GetFileList 方法以响应 Ray Chang 的评论

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

    【讨论】:

    • 您的this.GetFileList 方法代码在哪里? this 是什么?
    • @RayCheng 请参阅上面的编辑。这指的是 FTPClass.cs,这是我为 FTP 操作创建的一个类。
    • 我发现有些FTP服务器需要路径以“/”结尾,否则路径会被认为是文件路径,会应用目录监听上一级。
    【解决方案3】:

    试试这个:

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

    注意这一行using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())

    【讨论】:

    • 使用异常通常不是处理您期望发生的事情的好方法。减慢代码速度。最好从 FTP 服务器的根目录开始,执行一系列 ListDirectory 方法,直到确认所需的目录存在。
    • @mason:您认为可能搜索整个目录树比为此使用异常要快吗?我不这么认为。如果FtpWebRequest 有一个DirectoryExists() 方法,那就太好了。否则,我认为例外是合乎逻辑的方法。
    • 我在测试目录的存在时使用了类似的方法。但是,今天该代码不起作用。当目录不存在时,它不会抛出异常。我已经升级到 VS2013。尝试确定 .NET 中的某些行为是否发生了变化。
    • @JonathanWood 例外情况适用于您不希望发生并需要特殊处理的事情。它们不应该用于可以定期发生的事情。请参阅 MSDN 上的 Best Practices for Exceptions。在检查目录是否存在的方法中,我认为期望目录不经常存在是合理的。
    猜你喜欢
    • 1970-01-01
    • 2011-02-15
    • 2020-06-07
    • 2013-01-16
    • 2023-03-09
    • 1970-01-01
    • 2015-01-29
    • 2011-01-01
    • 1970-01-01
    相关资源
    最近更新 更多