• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 6177
  • Last Modified:

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

Steve Krile
Steve Krile
  • 2
  • 2
1 Solution
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.
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: http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic36703.aspx
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**@ftp.mysite.net/mysitesubdirectory/"
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

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now