c# - 如何检查FTP目录是否存在

标签 c# .net ftp ftpwebrequest

寻找通过 FTP 检查给定目录的最佳方法。

目前我有以下代码:

private bool FtpDirectoryExists(string directory, string username, string password)
{

    try
    {
        var request = (FtpWebRequest)WebRequest.Create(directory);
        request.Credentials = new NetworkCredential(username, password);
        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    }
    catch (WebException ex)
    {
        FtpWebResponse response = (FtpWebResponse)ex.Response;
        if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            return false;
        else
            return true;
    }
    return true;
}

无论目录是否存在,都会返回 false。有人能指出我正确的方向吗。

最佳答案

基本上捕获了我在创建目录时收到的错误。

private bool CreateFTPDirectory(string directory) {

    try
    {
        //create the directory
        FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(new Uri(directory));
        requestDir.Method = WebRequestMethods.Ftp.MakeDirectory;
        requestDir.Credentials = new NetworkCredential("username", "password");
        requestDir.UsePassive = true;
        requestDir.UseBinary = true;
        requestDir.KeepAlive = false;
        FtpWebResponse response = (FtpWebResponse)requestDir.GetResponse();
        Stream ftpStream = response.GetResponseStream();

        ftpStream.Close();
        response.Close();

        return true;
    }
    catch (WebException ex)
    {
        FtpWebResponse response = (FtpWebResponse)ex.Response;
        if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
        {
            response.Close();
            return true;
        }
        else
        {
            response.Close();
            return false;
        }  
    }
}

关于c# - 如何检查FTP目录是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2769137/

相关文章:

.net - 不寻常的整数编码到字节 - 这是什么方案?

c# - Excel Interop 获取单元格内文本的像素宽度

c# - 为 WPF 和 MVVM 中的模块(子) View 模型提供 "trigger-method"

c# - 如何清空 TableLayoutPanel

c# - PerfView:分析应用程序的性能,包括数据库调用

python - 通过 FTP 下载 zip 文件并在 Python 中提取内存中的文件

c# - Windows 10 开发 : How to refresh ListView whenever there is a change in the items inside ListView?

c# - 创建将具有类似于 Dictionary<T,T1> 对象初始值设定项的参数的 c# 方法

linux - 在 MacOS 中使用 mount_ftp 命令

powershell - 如何在PowerShell中的FTP服务器上查询文件,以确定是否需要上传?