FtpWebRequest删除指定文件夹内文件的函数代码
时间: 2023-12-07 17:06:13 浏览: 87
上传本地文件夹的文件到FTP服务器指定目录
3星 · 编辑精心推荐
以下是使用FtpWebRequest删除FTP服务器上指定文件夹内文件的代码示例:
```csharp
public static void DeleteFTPDirectory(string url, NetworkCredential credentials)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = credentials;
request.Method = WebRequestMethods.Ftp.ListDirectory;
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string line = reader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
string fileUrl = url + "/" + line;
if (line != "." && line != "..")
{
FtpWebRequest deleteRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
deleteRequest.Credentials = credentials;
deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile;
deleteRequest.GetResponse();
}
line = reader.ReadLine();
}
}
}
}
```
调用此方法时,需要传入FTP服务器的URL和凭据。注意,此方法将删除指定文件夹内的所有文件,但不会删除文件夹本身。如果需要删除文件夹本身,可以使用WebRequestMethods.Ftp.RemoveDirectory方法。
阅读全文