VB Methods to Truncate Files in a directory

Posted: 12/27/2011

These two methods will truncate files after a specified threshold in a directory. For instance, passing 20 in for the numberToKeep variable will keep the 20 newest files and delete everything else. The contents of the files themselves are not truncated.

Public Enum SortType
    LastWriteTime
    LastAccessTime
    CreationTime
End Enum
    

''' <summary>
''' Keeps the X specified newest files in a directory.  The rest of the files are deleted over the specified threshold.  This overload
''' uses the LastWriteTime to determine what files to keep.
''' </summary>
''' <param name="dir">The directory to truncate files in.  This does not recurse through child directories.</param>
''' <param name="numberToKeep">The number of files to keep.</param>
''' <remarks></remarks>
Public Shared Sub TruncateFiles(ByVal dir As String, ByVal numberToKeep As Integer)
    Call TruncateFiles(dir, numberToKeep, SortType.LastWriteTime)
End Sub

''' <summary>
''' Keeps the X specified newest files in a directory.  The rest of the files are deleted over the specified threshold.
''' </summary>
''' <param name="dir">The directory to truncate files in.  This does not recurse through child directories.</param>
''' <param name="numberToKeep">The number of files to keep.</param>
''' <param name="dateToUse">The date attribute to use.</param>
''' <remarks></remarks>
Public Shared Sub TruncateFiles(ByVal dir As String, ByVal numberToKeep As Integer, ByVal dateToUse As SortType)
    dir = dir.Trim("\")
    Dim di As DirectoryInfo = New DirectoryInfo(dir)
    Dim files As FileSystemInfo() = di.GetFileSystemInfos()
    Dim orderedFiles
    Select Case dateToUse
        Case SortType.CreationTime
            orderedFiles = files.OrderBy(Function(f) f.CreationTime).Reverse
        Case SortType.LastAccessTime
            orderedFiles = files.OrderBy(Function(f) f.LastAccessTime).Reverse
        Case SortType.LastWriteTime
            orderedFiles = files.OrderBy(Function(f) f.LastWriteTime).Reverse
        Case Else
            orderedFiles = files.OrderBy(Function(f) f.LastWriteTime).Reverse
    End Select
    Dim counter As Integer = 0
    For Each fi As FileInfo In orderedFiles
        counter += 1
        If counter > numberToKeep Then
            System.IO.File.Delete(fi.FullName)
        End If
    Next
End Sub