Geeks With Blogs


Add to Google

Tim Hibbard CEO for EnGraph software

We use this code to limit the size of directories in our Logger control.  The control will automatically export itself to an .xml file after it reaches a certain number of entries.  However we don't what that folder to get too big.  So this function gets the size of the directory and if it is larger than a certain size of MB, it will delete the oldest file.  It works recursively, so the directory size will always stay at a certain size.  It actually runs surprisingly quickly.

Private Sub TrimArchiveFolder(ByVal FilePath As String, ByVal MBLimit As Integer)
Dim Size As Long = 0
Dim LastFile As String = ""
Dim LastDate As Date = Now
Dim DI As New IO.DirectoryInfo(FilePath)
Dim FIS As IO.FileInfo() = DI.GetFiles
Dim FI As IO.FileInfo
For Each FI In FIS
If FI.LastWriteTime < LastDate Then
LastDate = FI.LastWriteTime
              LastFile = FI.FullName
End If
Size += FI.Length

If Size > MBLimit * 1000 * 1000 Then
If LastFile <> "" Then
             TrimArchiveFolder(FilePath, MBLimit)
End If
End If

Catch ex As Exception
End Try

End Sub

Posted on Wednesday, August 24, 2005 9:09 AM EnGraph , .NET , Controls | Back to top

Comments on this post: VB .NET - Limit the size of a directory

# re: VB .NET - Limit the size of a directory
Requesting Gravatar...
Very helpful, thanks. Modified it a bit to find the oldest file in a folder. AJ.
Left by AJ on Sep 22, 2006 2:18 AM

# re: VB .NET - Limit the size of a directory
Requesting Gravatar...
Basically what I was looking for, but, is there a way to loop through all subdirectories and subdirectories of subdirectories and so on as long as there are more subdirectories of subdirectories and get the total size of a single directory INCLUDING ALL subdirectories, subdirectories of subdirectories and so on?
Left by Leif on Nov 01, 2006 3:55 PM

Your comment:
 (will show your gravatar)

Copyright © Tim Hibbard | Powered by: