5

I'm using the following code for deleting all the files in a particular folder:

Sub DeleteFilesFromFolder(Folder As String)
    If Directory.Exists(Folder) Then
        For Each _file As String In Directory.GetFiles(Folder)
            File.Delete(_file)
        Next
        For Each _folder As String In Directory.GetDirectories(Folder)

            DeleteFilesFromFolder(_folder)
        Next

    End If

End Sub

Calling function:

DeleteFilesFromFolder("C:\New Folder")

Now, I want to delete all the *.pdf documents from new folder. How can I delete only the *.pdffiles from the folder (including the sub-folders)?

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
Dipojjal
  • 109
  • 1
  • 3
  • 10
  • 1
    Directory.GetFile should return the filename including the extension. If so it would be as simple as `IF _file.contains(".pdf") Then file.Delete(_file) END IF` Alternatively, add a filter to the GetFile http://stackoverflow.com/questions/163162/can-you-call-directory-getfiles-with-multiple-filters – Jonathon Cowley-Thom Aug 21 '14 at 15:08

2 Answers2

14

Directory.GetFiles() allows you to apply a search pattern and return you the files that match this pattern.

Sub DeleteFilesFromFolder(Folder As String)
    If Directory.Exists(Folder) Then
        For Each _file As String In Directory.GetFiles(Folder, "*.pdf")
            File.Delete(_file)
        Next
        For Each _folder As String In Directory.GetDirectories(Folder)
            DeleteFilesFromFolder(_folder)
        Next
    End If
End Sub

Check the MSDN link for more information: http://msdn.microsoft.com/en-us/library/wz42302f%28v=vs.110%29.aspx

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
2

You just have to check the extension before proceeding to deletion;

Sub DeleteFilesFromFolder(Folder As String)
If Directory.Exists(Folder) Then
    For Each _file As String In Directory.GetFiles(Folder)
       If System.IO.Path.GetExtension(_file) = ".pdf" Then  ' Check extension
          File.Delete(_file)
       End If
    Next
    For Each _folder As String In Directory.GetDirectories(Folder)
        DeleteFilesFromFolder(_folder)
    Next
End If
End Sub
Nadeem_MK
  • 7,533
  • 7
  • 50
  • 61