Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete all files of a particular type from a folder

Tags:

.net

vb.net

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)?

like image 875
Dipojjal Avatar asked Aug 21 '14 15:08

Dipojjal


People also ask

How do I delete all files from a certain name?

To delete matching files: enter *_bad. jpg in the search box, select the results and press Delete or Del.

How do you mass remove items from folders?

Deleting multiple files and folders To delete multiple items in a list hold down CTRL (Windows) or Œ˜ (Mac) while clicking on the desired items. Once you have selected all the items you would like to delete, scroll to the top of the file display area and click the Trash button.

How do I remove all files from a specific extension?

To remove a file with a particular extension, use the command 'rm'. This command is very easy to use, and its syntax is something like this. In the appropriate command, 'filename1', 'filename2', etc., refer to the names, plus their full paths.


1 Answers

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

like image 167
Tasos K. Avatar answered Sep 27 '22 00:09

Tasos K.