FTPClient如何删除目录?

发布于 2024-10-13 19:07:16 字数 65 浏览 7 评论 0原文

我想删除 FTP 中的一个文件夹。

FTPClient对象可以删除它吗?

I want to delete a folder in FTP.

Can FTPClient object delete it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

看轻我的陪伴 2024-10-20 19:07:16

要删除空目录,请使用 FtpWebRequestRemoveDirectory“方法”:

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 command = ListDirectoryDe​​tails 方法)并尝试解析特定于服务器的列表。许多 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();
}

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

尽管 Microsoft 不建议使用 FtpWebRequest一个新的发展


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

例如,使用 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();
} 

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

(我是 WinSCP 的作者)

To delete an empty directory, use the RemoveDirectory "method" of the FtpWebRequest:

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

use it like:

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

Though it gets a way more complicated, if you need to delete a non-empty directory. There's no support for recursive operations in FtpWebRequest class (or any other FTP implementation in the .NET framework). You have to implement the recursion yourself:

  • List the remote directory
  • Iterate the entries, deleting files and recursing into subdirectories (listing them again, etc.)

Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the FtpWebRequest. The FtpWebRequest unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.

Your options are:

  • Do an operation on a file name that is certain to fail for file and succeeds for directories (or vice versa). I.e. you can try to download the "name". If that succeeds, it's a file, if that fails, it's a directory. But that can become a performance problem, when you have a large number of entries.
  • You may be lucky and in your specific case, you can tell a file from a directory by a file name (i.e. all your files have an extension, while subdirectories do not)
  • You use a long directory listing (LIST command = ListDirectoryDetails method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format).
  • In this specific case, you can just try to delete the entry as a file. If deleting fails, try to list the entry as directory. If the listing succeeds, you assume it's a folder and proceed accordingly. Unfortunately some servers do not error, when you try to list a file. They will just return a listing with a single entry for the file.
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();
}

Use it the same way as the previous (flat) implementation.

Though Microsoft does not recommend FtpWebRequest for a new development.


Or use a 3rd party library that supports recursive operations.

For example with WinSCP .NET assembly you can delete whole directory with a single call to 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();
} 

Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.

(I'm the author of WinSCP)

蓝梦月影 2024-10-20 19:07:16

我发现工作的唯一方法是依赖“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 Direcotry Children

/* 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[] { "" };
            }

The only way I found working is to rely on "WebRequestMethods.Ftp.DeleteFile" and It will give an exception incase of folders or folders with files so I created a new interenal method to deletedirectory recursively
here is the code

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

and directory deletion

/* 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 Direcotry children

/* 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[] { "" };
            }
暗喜 2024-10-20 19:07:16

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();

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

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

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

FtpWebRequest provides the Delete action.
Here is a piece of code to achieve that :

               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();

It should work on files and directories. Indeed, please check that you have the right permissions.

Also, you could not delete folders while they are not empty. You must traverse them recursively to delete content before.

The exceptions thrown due to right permissions problems are not always very clear...

财迷小姐 2024-10-20 19:07:16

重要点

如上所述..

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

Important Point

As mentioned above..

you could not delete folders while they are not empty. You must traverse them recursively to delete content before.

源来凯始玺欢你 2024-10-20 19:07:16
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");
}

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

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

That's the code you can use.
And here's how you can use it, for example, on a button click.

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

And just remember that your folder should be EMPTY.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文