我在 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).
你能帮我删除一个文件夹吗
最佳答案
您为
DeleteFile
调用组合的 URL 是错误的。与:
path = "ftp://ftp.example.com/" + "/" + ff; string server = "ftp://ftp.example.com/";
ftpURL + "/"+ ftpDirectory
是ftp://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);
无论如何,您都无法使用
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/