Deleting All Files in an FTP Directory using VB.Net 2.0 and FTPWebRequest

I am trying to write some VB code to delete files in an FTP directory.  If I know the name of the file, I have no problems doing this.  However, I would like to delete *any* file in the folder.  My first thought (in the code below which DOES NOT WORK) was to use a wildcard.  Anyone out there know of a way using FTPWebRequest to delete all files in a directory?

In the example below, the part that doesn't work is
   Dim filename As String = ftpURI & "*.xml"

If I replace the "*" with the name of a file I can see in the directory, then the rest of the code executes just fine.
    Dim filename As String = ftpURI & "*.xml"
    Dim ftpReq As FtpWebRequest = WebRequest.Create(filename)
    ftpReq.Method = WebRequestMethods.Ftp.DeleteFile
    ftpReq.Credentials = New NetworkCredential("anonymous", "password")
    Dim ftpResp As FtpWebResponse = ftpReq.GetResponse
Catch ex As Exception
End Try

Open in new window

LVL 16
Steve KrileAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Shaun KlineLead Software EngineerCommented:
Would doing a WebRequestMethods.FTP.ListDirectory or ListDirectoryDetail work? This would return the directory listing which you could parse for the file names, and then delete each file.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Steve KrileAuthor Commented:
I looked at that, but before jumping off that cliff (parsing can be ugly) I wanted to know if there was some sort of "delete all" capability.
Shaun KlineLead Software EngineerCommented:
It appears that the FTPWebRequest.Method only supports a limited number of FTP commands (probably geared towards the IIS FTP server). You may be "stuck" using the ListDirectory method. It appears that this method can return a simple directory listing, where the file names are line return delimited (which would allow you to do a split on the returned string). This link may help:
Steve KrileAuthor Commented:
I'm guessing Shaun is most correct.  And for anyone interested, this is how I came up with a way of doing this.
Const ftpURI As String = "ftp://**username**:**password**"
On a button click or something:
            'get a list of the files in the target directory of my ftp site
            Dim fileString As String = GetFileArray()
            'split the list into a string array
            Dim fileArr() As String = Split(fileString, vbCrLf)
            'create an incrementing variable
            Dim i As Integer = 0
            'loop through the file names
            For i = 0 To UBound(fileArr)
                'if there actually is a file name, delete it
                If fileArr(i).Length > 0 Then
                End If
    Protected Sub DeleteFTPFile(ByVal FileName As String)
            'give simple file name a fully qualified locatin (based on my ftpURI contstant)
            Dim ftpfilename As String = ftpURI & FileName
            'create a FTPWebRequest object
            Dim ftpReq As FtpWebRequest = WebRequest.Create(ftpfilename)
            'set the method to delete the file
            ftpReq.Method = WebRequestMethods.Ftp.DeleteFile
            'delete the file
            Dim ftpResp As FtpWebResponse = ftpReq.GetResponse
        Catch ex As Exception
            'spot to do error handling
        End Try
    End Sub
    Protected Function GetFileArray() As String
        Dim result As String = ""
            'create new webrequest using my Constant ftpURI string
            Dim ftpReq As FtpWebRequest = WebRequest.Create(ftpURI)
            'set the method to list directory
            ftpReq.Method = WebRequestMethods.Ftp.ListDirectoryDetails
            'get the response
            Dim FTPResp As FtpWebResponse = ftpReq.GetResponse
            'add the response to a Stream object
            Dim ftpRespStream As Stream = FTPResp.GetResponseStream
            'read the response stream object
            Dim reader As StreamReader
            reader = New StreamReader(ftpRespStream, System.Text.Encoding.UTF8)
            'convert the stream object to a string
            Dim strHTML As String
            strHTML = reader.ReadToEnd
            'split the string by line feed
            Dim strArr() As String
            strArr = Split(strHTML, vbCrLf)
            'create a string builder that will eventually hold ONLY file names
            Dim FileSB As StringBuilder = New StringBuilder()
            'create two integers for looping purposes
            Dim i As Integer = 0
            Dim z As Integer = 0
            'text that we want to find a match for - this could be a file name, or extension, or
            'folder name or whatever.  In my case, I am looking for any .xml files. 
            Dim matchText As String = ".xml"
            'start looping through each item in the file listing
            For i = 0 To UBound(strArr)
                'create a new string array
                Dim parseArr() As String
                'split the file listing by spaces - there will be a lot of nonsense that we
                'will ignore - instead, we will be looking for anything that has our defined text in it
                parseArr = Split(strArr(i), " ")
                'loop through the new string array
                For z = 0 To UBound(parseArr)
                    'if it contains the matching text, add it to our stringbuilder
                    If InStr(parseArr(z), matchText) Then
                    End If
            result = FileSB.ToString()
        Catch ex As Exception
        End Try
        Return result
    End Function

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.