Simone Bosio
Simone Bosio

Reputation: 45

Delete FTP files with name containing a string (matching mask)

I would like to delete all files on an FTP server, whose names contain a certain string.

For example I have these files on the FTP:

pippo_1.jpg
pippo_2.jpg
pippo_3.jpg
pluto_1.jpg

I would like delete all file that contain pippo.

How can I delete all these files with a single operation?

Thank you!

Upvotes: 2

Views: 3252

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202474

No implementation of the FTP protocol in .NET framework allows this in a single operation.

You have to list the remote directory, filter the files you want to delete and delete them one by one.


If you really want to do this in a single operation, you have use a 3rd party library, that supports operations with file masks. For example WinSCP .NET assembly allows this with its 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

(I'm the author of WinSCP)


If you do not want to use a 3rd party library, do as suggested above:

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

Upvotes: 3

Related Questions