首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FTPClient如何删除目录?

问FTPClient如何删除目录?
EN

Stack Overflow用户
提问于 2011-01-26 02:41:33
回答 5查看 17.2K关注 0票数 2

我想删除FTP中的文件夹。

FTPClient object可以删除它吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-01-26 03:40:40

FtpWebRequest提供了删除操作。下面是实现这一点的一段代码:

代码语言:javascript
复制
               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();

它应该可以在文件和目录上工作。确实,请检查您是否拥有正确的权限。

此外,您不能在文件夹不为空时将其删除。您必须递归地遍历它们以删除之前的内容。

由于权限问题而抛出的异常并不总是非常清楚...

票数 1
EN

Stack Overflow用户

发布于 2016-09-09 21:29:57

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

代码语言:javascript
复制
void DeleteFtpDirectory(string url, NetworkCredential credentials)
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Ftp.RemoveDirectory;
    request.Credentials = credentials;
    request.GetResponse().Close();
}

像这样使用它:

代码语言:javascript
复制
string url = "ftp://ftp.example.com/directory/todelete";
NetworkCredential credentials = new NetworkCredential("username", "password");
DeleteFtpDirectory(url, credentials);

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

列出remote directory

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

棘手的部分是从子目录中识别文件。在FtpWebRequest中,无法以可移植的方式做到这一点。遗憾的是,FTP不支持MLSD命令,该命令是在FtpWebRequest协议中检索带有文件属性的目录列表的唯一可移植方法。另请参见Checking if object on FTP server is file or directory。

您可以选择:

  • 对文件名执行的操作对于文件肯定会失败,而对于目录肯定会成功(反之亦然)。也就是说,您可以尝试下载“名称”。如果成功,它就是一个文件,如果失败,它就是一个目录。
  • 你可能很幸运,在你的特殊情况下,你可以通过文件名来区分文件和目录(即你所有的文件都有扩展名,而子目录没有)
  • 你使用一个长的目录列表(LIST
  • = ListDirectoryDetails方法),并尝试解析特定于服务器的列表。许多FTP服务器使用*nix样式的列表,在这种列表中,您通过条目开头的d来标识目录。但许多服务器使用不同的格式。下面的示例使用这种方法(假设格式为*nix )。
  • 在此特定情况下,您可以尝试将条目作为文件删除。如果删除失败,请尝试将该条目列为目录。如果清单成功,您将假定它是一个文件夹,并相应地继续操作。不幸的是,当您尝试列出文件时,某些服务器不会出错。它们将只返回一个列表,其中包含该文件的单个条目。

代码语言:javascript
复制
static void DeleteFtpDirectory(string url, NetworkCredential credentials)
{
    FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url);
    listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    listRequest.Credentials = credentials;

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

    using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
    using (Stream listStream = listResponse.GetResponseStream())
    using (StreamReader 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
        {
            FtpWebRequest deleteRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
            deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile;
            deleteRequest.Credentials = credentials;

            deleteRequest.GetResponse();
        }
    }

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

    removeRequest.GetResponse();
}

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

虽然Microsoft does not recommend FtpWebRequest for a new development。

或者使用支持递归操作的第三方库。

例如,使用WinSCP .NET assembly,只需调用一次Session.RemoveFiles即可删除整个目录

代码语言:javascript
复制
// 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();
} 

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

(我是WinSCP的作者)

票数 10
EN

Stack Overflow用户

发布于 2014-03-25 09:07:30

我发现唯一有效的方法是依靠"WebRequestMethods.Ftp.DeleteFile“,它会在文件夹或包含文件的文件夹中给出一个异常,所以我创建了一个新的内部方法来递归地删除目录,这是代码

代码语言:javascript
复制
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;
            }

和目录删除

代码语言:javascript
复制
/* 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;
            }

列出目录尝试子项

代码语言:javascript
复制
/* 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[] { "" };
            }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4797508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档