我想删除FTP服务器上的所有文件,其名称包含某个字符串。
例如我在FTP上有这些文件:
pippo_1.jpg
pippo_2.jpg
pippo_3.jpg
pluto_1.jpg
我想删除包含pippo
的所有文件。
如何通过一次操作删除所有这些文件?
谢谢!
答案 0 :(得分:3)
在.NET框架中没有实现FTP协议允许在单个操作中使用它。
您必须列出远程目录,过滤要删除的文件并逐个删除。
如果您真的想在一次操作中执行此操作,则可以使用第三方库,该库支持使用文件掩码进行操作。例如,WinSCP .NET assembly允许使用Session.RemoveFiles
method:
Dim sessionOptions As New SessionOptions
With sessionOptions
.Protocol = Protocol.Ftp
.HostName = "ftp.example.com"
.UserName = "username"
.Password = "password"
End With
Using session As New Session
session.Open(sessionOptions)
session.RemoveFiles("/remote/path/pippo*").Check()
End Using
(我是WinSCP的作者)
如果您不想使用第三方库,请按照上面的建议进行操作:
Dim url As String = "ftp://ftp.example.com/remote/path/"
Dim credentials As NetworkCredential = New NetworkCredential("username", "password")
Dim listRequest As FtpWebRequest = WebRequest.Create(url)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
listRequest.Credentials = credentials
Using listResponse As FtpWebResponse = listRequest.GetResponse(),
listStream As Stream = listResponse.GetResponseStream(),
listReader As StreamReader = New StreamReader(listStream)
While Not listReader.EndOfStream
Dim filename As String = listReader.ReadLine()
If filename.StartsWith("pippo") Then
Dim deleteRequest As FtpWebRequest = WebRequest.Create(url + filename)
deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile
deleteRequest.Credentials = credentials
deleteRequest.GetResponse()
End If
End While
End Using