Visual Basic Programming Code Examples
Visual Basic > Files Directories Drives Code Examples
Delete files in a directory which match a criteria
Delete files in a directory which match a criteria
The following code demonstrates how to delete/kill all the files in a specific directory which match either a file pattern or older than a specific date.
'Purpose : Deletes all the files in a directory which match the specified criteria
'Inputs : sDirectory The directory to delete this files in
' [sFilePattern] The file pattern to delete. eg. "*.xls"
' [dtModifiedOlderThan] If specified, deletes all files with a last
' modified date less than this date.
'Outputs : Returns the number of files deleted or -1 on error.
'Notes : If both parameters are specified then both have to be satified before the file will be deleted.
' Requires SCRRUN.DLL ("Microsoft Scripting Runtime")
'Revisions :
Function FilesDelete(sDirectory As String, Optional sFilePatern As String, Optional dtModifiedOlderThan As Date) As Long
Dim oFSO As Object 'Scripting.FileSystemObject
Dim oDirectory As Object 'Scripting.Folder
Dim oThisFile As Object 'Scripting.File
Dim lCountDeleted As Long, bDeleted As Boolean
On Error GoTo ErrFailed
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oDirectory = oFSO.GetFolder(sDirectory)
'Loop through all the files in the directory
For Each oThisFile In oDirectory.Files
bDeleted = False
If dtModifiedOlderThan Then
'Check file date
If Len(sFilePatern) Then
'Check file name pattern and date
If oThisFile.Name Like sFilePatern And oThisFile.DateLastModified < dtModifiedOlderThan Then
'Delete old file
lCountDeleted = lCountDeleted + 1
oThisFile.Delete True
bDeleted = True
End If
ElseIf oThisFile.DateLastModified < dtModifiedOlderThan Then
'Delete old file
lCountDeleted = lCountDeleted + 1
oThisFile.Delete True
bDeleted = True
End If
ElseIf oThisFile.Name Like sFilePatern Then
'Delete matching file
lCountDeleted = lCountDeleted + 1
oThisFile.Delete True
End If
Next
Set oThisFile = Nothing
Set oDirectory = Nothing
Set oFSO = Nothing
If FilesDelete = 0 Then
'Return success
FilesDelete = lCountDeleted
End If
Exit Function
ErrFailed:
Debug.Assert False
Debug.Print "Error in FilesDelete: " & Err.Description
FilesDelete = -1
Resume Next
End Function
Sub Test()
'Delete all mdb files older than a 28 days
FilesDelete "C:\Web\Support\database\archive", "*.mdb", Now - 28
End Sub