C#删除FTP文件夹(有子文件夹和子文件)的方法
作者:野牛程序员:2023-12-28 20:06:10C#阅读 2369
可以使用FtpWebRequest
和WebRequestMethods.Ftp
类来实现删除FTP服务器上的文件夹及其内容。以下是一个示例的C#代码:
using System; using System.Net; class Program { static void Main() { string ftpServer = "ftp://yourftpserver.com/"; string folderToDelete = "folderToDelete"; DeleteFtpDirectory(ftpServer, folderToDelete); Console.WriteLine("删除完成。"); } static void DeleteFtpDirectory(string ftpServer, string folderToDelete) { // 构建FTP路径 string ftpPath = $"{ftpServer}/{folderToDelete}/"; // 创建FTP请求对象 FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpPath); ftpRequest.Credentials = new NetworkCredential("username", "password"); ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; try { // 获取FTP目录列表 using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse()) { using (System.IO.StreamReader streamReader = new System.IO.StreamReader(ftpResponse.GetResponseStream())) { // 读取目录列表 string fileList = streamReader.ReadToEnd(); string[] files = fileList.Split(new string[] { "\\r\\n" }, StringSplitOptions.RemoveEmptyEntries); // 遍历目录并删除文件和子目录 foreach (string file in files) { string fileName = file.Split(new char[] { ' ', '\\t' }, StringSplitOptions.RemoveEmptyEntries).Last(); if (fileName != "." && fileName != "..") { if (file.StartsWith("d")) // 如果是目录 { DeleteFtpDirectory(ftpPath, fileName); } else // 如果是文件 { DeleteFtpFile(ftpPath, fileName); } } } } } // 删除空目录 FtpWebRequest ftpRemoveRequest = (FtpWebRequest)WebRequest.Create(ftpPath); ftpRemoveRequest.Credentials = new NetworkCredential("username", "password"); ftpRemoveRequest.Method = WebRequestMethods.Ftp.RemoveDirectory; FtpWebResponse ftpRemoveResponse = (FtpWebResponse)ftpRemoveRequest.GetResponse(); ftpRemoveResponse.Close(); } catch (WebException ex) { Console.WriteLine($"删除FTP目录失败:{ex.Message}"); } } static void DeleteFtpFile(string ftpPath, string fileName) { // 创建FTP请求对象 FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create($"{ftpPath}/{fileName}"); ftpRequest.Credentials = new NetworkCredential("username", "password"); ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile; try { // 删除文件 FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpResponse.Close(); } catch (WebException ex) { Console.WriteLine($"删除FTP文件失败:{ex.Message}"); } } }
请注意,替换代码中的"yourftpserver.com"、"username"和"password"为实际的FTP服务器地址、用户名和密码。此代码将递归删除指定的FTP文件夹及其内容。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892