||There are many situations in which you may wish to delete all files containing a certain file extension in a certain directory. The naive approach to solving this problem would involve iterating through all of the files in the directory and checking the file extension for each file - if it matched the criteria, the file would be deleted. While such an approach would work, there's a much easier way to accomplish the same task.|
DeleteFile method of the FileSystemObject can accept wildcards. That means, you can call
DeleteFile like so:
to delete all of the
.txt files in
C:\SomeDirectory. Neat, eh? In fact, you can use wildcards other than the
*, such as the
Well, it isn't that easy, there is one catch. If there are no files in the directory that match the wildcard expression the
DeleteFile method will raise an error, saying it couldn't delete the specified file. Hence, before using the
DeleteFile method with wildcards you should turn off error handling via a
On Error Resume Next statement. To learn more about error handling in VBScript be sure to read: Error Handling in ASP.
Now, if you wanted to allow the user to delete multiple file extensions, you'll need to call the
DeleteFile method multiple times. Below you'll find a function that accepts two input parameters:
strWildcards - a comma-delimited list of wildcards to delete.
strDirectory - the directory to delete the files from (must end with a backslash).
Sub DeleteFileExtensions(strWildcards, strDirectory)
'Turn off error handling
On Error Resume Next
'Create an instance of the FileSystemObject
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Loop through each wildcard extension to delete
aExtensions = split(strWildcards, ",")
For i = LBound(aExtensions) to UBound(aExtensions)
'Delete the file
objFSO.DeleteFile(strDirectory & aExtensions(i))
That's all you have to do! To utilize this function you could use the following code:
Dim strWildcardsToDelete, strDirectory
strDirectory = "C:\SomeDirectory"
strWildcardsToDelete = "*.txt,*.inc"
DeleteFileExtensions strWildcardsToDelete, strDirectory
To learn more about the
DeleteFile method be sure to read the technical docs. To learn more about the
split function (used in the
DeleteFileExtensions function), be sure to read: Parsing with join and split.