• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1460
  • Last Modified:

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?
1 Solution
This is set to 10 files.

Sub FindFiles()
    Dim strFileName As String
    Dim strOldestFile As String
    Dim strFolder As String
    Dim iFileCount As Integer
    Dim i As Integer
    Dim dt As Date
    strFolder = "C:\MyFolder"
    strFileName = Dir$(strFolder & "\*")
    strOldestFile = strFileName
    dt = FileDateTime(strFolder & "\" & strFileName)
    Do Until strFileName = ""
    Debug.Print strFileName, FileDateTime(strFolder & "\" & strFileName),
        If (FileDateTime(strFolder & "\" & strFileName)) < dt Then
            dt = FileDateTime(strFolder & "\" & strFileName)
            strOldestFile = strFileName
        End If
        i = i + 1
        strFileName = Dir$()
    If i > 10 Then
        Kill strFolder & "\" & strOldestFile
    End If
End Sub
Mike_StevensAuthor Commented:
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
  'Delete oldest file:
  fso.DeleteFile oldestFile
  MsgBox oldestFile & " deleted"
End If

End Sub

Mauricio GarciaSystems AdminCommented:
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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now