c# - 删除FTP服务器中的文件夹和子文件夹

标签 c# winforms ftp ftpwebrequest

我在 FTP 服务器中创建了包含年、月和日期的文件夹,在登录到服务器后我们可以看到在年创建的文件夹,当我点击那年时它显示月份,当我点击月份时它显示日期。现在我需要删除这个文件夹。

下面是我删除FTP服务器文件夹的代码

FtpWebResponse responseFileDelete = (FtpWebResponse)ftpRequest.GetResponse();

An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The remote server returned an error: (550) File unavailable (e.g., file not found, no access).

你能帮我删除一个文件夹吗

最佳答案

  1. 您为 DeleteFile 调用组合的 URL 是错误的。

    与:

    path = "ftp://ftp.example.com/" + "/" + ff;
    string server = "ftp://ftp.example.com/";
    

    ftpURL + "/"+ ftpDirectoryftp://ftp.example.com/ftp://ftp.example.com//dir 而你想要 ftp://ftp.example.com//dir 或者 ftp://ftp.example.com/dir

    仅使用 ftpDirectory

    FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpDirectory);
    
  1. 无论如何,您都无法使用 WebRequestMethods.Ftp.DeleteFile 删除文件夹。你必须使用 WebRequestMethods.Ftp.RemoveDirectory .

    ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
    

    但请注意,即使是 .RemoveDirectory 也只能删除一个空目录。

    您必须先递归删除文件夹的文件和子文件夹,然后才能删除文件夹本身。

    使用 FtpWebRequest 实现递归并不容易,特别是因为它不支持 MLSD 命令(区分文件和文件夹的唯一可靠方法)。详情看我对C# Download all files and subdirectories through FTP的回答.


    或者,使用另一个支持递归操作的 FTP 库。

    例如 WinSCP .NET assembly , 你可以使用 Session.RemoveFiles在一次调用中删除文件夹及其内容:

    SessionOptions sessionOptions = new SessionOptions
    {
        Protocol = Protocol.Ftp,
        HostName = "ftp.example.com",
        UserName = "username",
        Password = "mypassword",
    };
    
    using (Session session = new Session())
    {
        session.Open(sessionOptions);
        session.RemoveFiles("/" + ff);
    }
    

    (我是 WinSCP 的作者)

关于c# - 删除FTP服务器中的文件夹和子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37496226/

相关文章:

c# - Sublime Text : How to recognize (and highlight) C# . NET 类、方法和属性名称?

c# - 在运行时在 GridView 中逐行添加

c# - 递归失败

c# - DataGridViewComboBoxColumn 中的非字符串值导致 DataGridView 中的数据错误

从 ftp 服务器读取 xlsx(使用 RCurl)

Java 和 FTP 编辑在线文本文件

c# - datagridview 文本框中的列总和

c# - 有没有办法在用户单击另一行中的单元格时保持选中 DataGridView 行?

c# - C# 中服务器客户端应用程序的 UDP 数据报代码

java - 如何使用相同的 TLS session 通过数据连接连接到 FTPS 服务器?