How to delete all files of a specific type from a folder
I am using the following code to delete all files in a specific 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
Call function:
DeleteFilesFromFolder("C:\New Folder")
Now I want to delete all documents *.pdf
from the new folder. How do I delete only files *.pdf
from a folder (including subfolders)?
+3
source to share
2 answers
Directory.GetFiles()
allows you to apply a search pattern and return files that match that pattern to you.
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 MSDN link for more information: http://msdn.microsoft.com/en-us/library/wz42302f%28v=vs.110%29.aspx
+9
source to share
You just need to check the extension before proceeding with its removal;
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
+2
source to share