Link to home
Start Free TrialLog in
Avatar of Mike_Stevens
Mike_StevensFlag for United States of America

asked on

Delete oldest file in folder using visual basic 6

I need to be to count the number of files in a folder using visual basic 6.  If the file count exceeds a per determined number of files I need to the determine which file is the oldest and then delete the oldest file.  Can this be done?  Does anybody have any examples?
ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mike_Stevens

ASKER

Awesome...thanks
Here's an alternative function for you.  Just add a reference to the Microsoft Scripting Runtime...

Public Sub PurgeFile(ByVal path As String, ByVal numberOfFiles As Integer)

Dim fso As New FileSystemObject
Dim fldr As Folder
Set fldr = fso.GetFolder(path)

Dim fil As File
Dim oldestDate As Date
Dim oldestFile As String
oldestDate = Date  'Set to today's date

If fldr.Files.Count >= numberOfFiles Then
   
  For Each fil In fldr.Files
 
    If fil.DateLastModified < oldestDate Then
        oldestFile = fil.path
    End If
   
  Next
   
  'Delete oldest file:
  fso.DeleteFile oldestFile
  MsgBox oldestFile & " deleted"
 
End If

End Sub

Hello VBRocks, I have found your code very helpful. How in that code, I can specify the extension of the file? I mean, for example, only to delete .txt files, or .pdf files.

Thanks.