Your source for ASP-related frequently asked questions and answers! : ASP FAQS : FileSystemObject

Question: How can I delete files by extension in a given directory? What if I have multiple file extension names I want to delete?

Answer: 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.

Th 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
  Dim objFSO
  Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

  'Loop through each wildcard extension to delete
  Dim aExtensions
  aExtensions = split(strWildcards, ",")

  Dim i
  For i = LBound(aExtensions) to UBound(aExtensions)
    'Delete the file
    objFSO.DeleteFile(strDirectory & aExtensions(i))
End Sub

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.

Happy Programming!

FAQ posted by Scott Mitchell at 12/16/2001 12:47:36 PM to the FileSystemObject category. This FAQ has been viewed 81,511 times.

Copyright 2018 QuinStreet Inc. All Rights Reserved.
Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers