2

我想删除 FTP 中的文件夹。

对象可以FTPClient删除吗?

4

5 回答 5

11

要删除空目录,请使用以下RemoveDirectory“方法” FtpWebRequest

void DeleteFtpDirectory(string url, NetworkCredential credentials)
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Ftp.RemoveDirectory;
    request.Credentials = credentials;
    request.GetResponse().Close();
}

像这样使用它:

string url = "ftp://ftp.example.com/directory/todelete";
NetworkCredential credentials = new NetworkCredential("username", "password");
DeleteFtpDirectory(url, credentials);

尽管它变得更加复杂,但如果您需要删除一个非空目录。不支持FtpWebRequest类中的递归操作(或 .NET 框架中的任何其他 FTP 实现)。您必须自己实现递归:

  • 列出远程目录
  • 迭代条目,删除文件并递归到子目录(再次列出它们等)

棘手的部分是从子目录中识别文件。没有办法以便携的方式使用FtpWebRequest. 不幸的FtpWebRequest是不支持该MLSD命令,这是在 FTP 协议中检索具有文件属性的目录列表的唯一可移植方式。另请参阅检查 FTP 服务器上的对象是文件还是目录

您的选择是:

  • 对文件名执行操作,对于文件肯定会失败,而对于目录会成功(反之亦然)。即您可以尝试下载“名称”。如果成功,它是一个文件,如果失败,它是一个目录。但是,当您有大量条目时,这可能会成为性能问题。
  • 您可能很幸运,在您的特定情况下,您可以通过文件名来区分目录中的文件(即所有文件都有扩展名,而子目录没有)
  • 您使用长目录列表(LIST命令 =ListDirectoryDetails方法)并尝试解析特定于服务器的列表。许多 FTP 服务器使用 *nix 样式的列表,您可以通过d条目开头的 来标识目录。但是许多服务器使用不同的格式。以下示例使用这种方法(假设 *nix 格式)。
  • 在这种特定情况下,您可以尝试将条目作为文件删除。如果删除失败,请尝试将条目列为目录。如果列表成功,您假设它是一个文件夹并相应地继续。不幸的是,当您尝试列出文件时,某些服务器不会出错。他们只会返回一个包含单个文件条目的列表。
static void DeleteFtpDirectory(string url, NetworkCredential credentials)
{
    var listRequest = (FtpWebRequest)WebRequest.Create(url);
    listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    listRequest.Credentials = credentials;

    List<string> lines = new List<string>();

    using (var listResponse = (FtpWebResponse)listRequest.GetResponse())
    using (Stream listStream = listResponse.GetResponseStream())
    using (var listReader = new StreamReader(listStream))
    {
        while (!listReader.EndOfStream)
        {
            lines.Add(listReader.ReadLine());
        }
    }

    foreach (string line in lines)
    {
        string[] tokens =
            line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
        string name = tokens[8];
        string permissions = tokens[0];

        string fileUrl = url + name;

        if (permissions[0] == 'd')
        {
            DeleteFtpDirectory(fileUrl + "/", credentials);
        }
        else
        {
            var deleteRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
            deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile;
            deleteRequest.Credentials = credentials;

            deleteRequest.GetResponse();
        }
    }

    var removeRequest = (FtpWebRequest)WebRequest.Create(url);
    removeRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
    removeRequest.Credentials = credentials;

    removeRequest.GetResponse();
}

使用与之前的(平面)实现相同的方式。

虽然微软不推荐FtpWebRequest新的开发


或者使用支持递归操作的 3rd 方库。

例如,使用WinSCP .NET 程序集,您可以通过一次调用来删除整个目录Session.RemoveFiles

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Delete folder
    session.RemoveFiles("/directory/todelete").Check();
} 

MLSD如果服务器支持,WinSCP 在内部使用该命令。如果没有,它会使用该LIST命令并支持数十种不同的列表格式。

(我是WinSCP的作者)

于 2016-09-09T13:29:57.417 回答
4

我发现工作的唯一方法是依赖“WebRequestMethods.Ftp.DeleteFile”,如果文件夹或带有文件的文件夹会出现异常,所以我创建了一个新的内部方法来递归地删除目录这里是代码

public void delete(string deleteFile)
            {
                try
                {
                    /* Create an FTP Request */
                    ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + deleteFile);
                    /* Log in to the FTP Server with the User Name and Password Provided */
                    ftpRequest.Credentials = new NetworkCredential(user, pass);
                    /* When in doubt, use these options */
                    ftpRequest.UseBinary = true;
                    ftpRequest.UsePassive = true;
                    ftpRequest.KeepAlive = true;
                    /* Specify the Type of FTP Request */
                    ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                    /* Establish Return Communication with the FTP Server */
                    ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                    /* Resource Cleanup */
                    ftpResponse.Close();
                    ftpRequest = null;
                }
                catch (Exception ex) { 
                    //Console.WriteLine(ex.ToString()); 
                    try
                    {
                        deleteDirectory(deleteFile);
                    }
                    catch { }


                }
                return;
            }

和目录删除

/* Delete Directory*/
            private void deleteDirectory(string directoryName)
            {
                try
                {
                    //Check files inside 
                    var direcotryChildren  = directoryListSimple(directoryName);
                    if (direcotryChildren.Any() && (!string.IsNullOrWhiteSpace(direcotryChildren[0])))
                    {
                        foreach (var child in direcotryChildren)
                        {
                            delete(directoryName + "/" +  child);
                        }
                    }


                    /* Create an FTP Request */
                    ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + directoryName);
                    /* Log in to the FTP Server with the User Name and Password Provided */
                    ftpRequest.Credentials = new NetworkCredential(user, pass);
                    /* When in doubt, use these options */
                    ftpRequest.UseBinary = true;
                    ftpRequest.UsePassive = true;
                    ftpRequest.KeepAlive = true;
                    /* Specify the Type of FTP Request */
                    ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;

                    /* Establish Return Communication with the FTP Server */
                    ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                    /* Resource Cleanup */
                    ftpResponse.Close();
                    ftpRequest = null;
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                return;
            }

列出目录孩子

/* List Directory Contents File/Folder Name Only */
            public string[] directoryListSimple(string directory)
            {
                try
                {
                    /* 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);
                    /* When in doubt, use these options */
                    ftpRequest.UseBinary = true;
                    ftpRequest.UsePassive = true;
                    ftpRequest.KeepAlive = true;
                    /* Specify the Type of FTP Request */
                    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                    /* Establish Return Communication with the FTP Server */
                    ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                    /* Establish Return Communication with the FTP Server */
                    ftpStream = ftpResponse.GetResponseStream();
                    /* Get the FTP Server's Response Stream */
                    StreamReader ftpReader = new StreamReader(ftpStream);
                    /* Store the Raw Response */
                    string directoryRaw = null;
                    /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
                    try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
                    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                    /* Resource Cleanup */
                    ftpReader.Close();
                    ftpStream.Close();
                    ftpResponse.Close();
                    ftpRequest = null;
                    /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
                    try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; }
                    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                /* Return an Empty string Array if an Exception Occurs */
                return new string[] { "" };
            }

            /* List Directory Contents in Detail (Name, Size, Created, etc.) */
            public string[] directoryListDetailed(string directory)
            {
                try
                {
                    /* 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);
                    /* When in doubt, use these options */
                    ftpRequest.UseBinary = true;
                    ftpRequest.UsePassive = true;
                    ftpRequest.KeepAlive = true;
                    /* Specify the Type of FTP Request */
                    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                    /* Establish Return Communication with the FTP Server */
                    ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                    /* Establish Return Communication with the FTP Server */
                    ftpStream = ftpResponse.GetResponseStream();
                    /* Get the FTP Server's Response Stream */
                    StreamReader ftpReader = new StreamReader(ftpStream);
                    /* Store the Raw Response */
                    string directoryRaw = null;
                    /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
                    try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
                    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                    /* Resource Cleanup */
                    ftpReader.Close();
                    ftpStream.Close();
                    ftpResponse.Close();
                    ftpRequest = null;
                    /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
                    try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; }
                    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                /* Return an Empty string Array if an Exception Occurs */
                return new string[] { "" };
            }
于 2014-03-25T01:07:30.183 回答
1

FtpWebRequest 提供删除操作。这是一段代码来实现这一点:

               FtpWebRequest reqFTP = FtpWebRequest.Create(uri);
                // Credentials and login handling...

                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                string result = string.Empty;
                FtpWebResponse response = reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();

它应该适用于文件和目录。确实,请检查您是否拥有正确的权限。

此外,当文件夹不为空时,您无法删除它们。您必须递归遍历它们才能删除内容。

由于正确的权限问题引发的异常并不总是很清楚......

于 2011-01-25T19:40:39.587 回答
-2

很重要的一点

正如刚才提到的..

当文件夹不为空时,您无法删除它们。您必须递归遍历它们才能删除内容。

于 2014-02-13T13:01:50.473 回答
-2
public void Deletedir(string remoteFolder)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/"+ remoteFolder);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;***strong text***
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Get the FTP Server's Response Stream */
        ftpStream = ftpResponse.GetResponseStream();
        /* Open a File Stream to Write the Downloaded File */
    }
    catch { }
}

这就是您可以使用的代码。这是您如何使用它的方法,例如,在单击按钮时。

private void button5_Click(object sender, EventArgs e)
{
    ftp ftpClient = new ftp(@"SERVICE PROVIDER", "USERNAME", "PASSWORD");
    ftpClient.Deletedir("DIRECTORY U WANT TO DELETE");
}

请记住,您的文件夹应该是空的。

于 2015-04-08T18:49:50.080 回答