Kuzon
Kuzon

Reputation: 822

How to find the oldest Folder in a Folder vb.net

I am trying to make a program that backs up folders. I want to have say 5 folders, then if it is backed up again I want the oldest of the 5 folders to be deleted and the new one placed in it.

How would I find the oldest folder in a directory

Upvotes: 0

Views: 2766

Answers (1)

Ash Clarke
Ash Clarke

Reputation: 4887

Using System.IO.DirectoryInfo could be helpful.

Specifically with regards to the CreationTime property and EnumerateDirectories method.

Here is a modified sample for the EnumerateDirectories method using LINQ:

' Create a DirectoryInfo of the Program Files directory.
Dim dirPrograms As New DirectoryInfo("c:\program files")

' LINQ query for oldest directory
Dim dir = (From dir In dirPrograms.EnumerateDirectories()).Min(function (o) o.CreationTime).FirstOrDefault()

If Not IsNothing(dir) Then
' perform rest of function
End If

Here is a non LINQ version to get the oldest directory in a folder:

    Dim di As New DirectoryInfo("C:\program files")
    Dim dirs() as DirectoryInfo = di.GetDirectories()
    Dim creationTime as DateTime = DateTime.Now
    Dim oldestDir As DirectoryInfo

    For Each dir As DirectoryInfo In dirs
        If DateTime.Compare(dir.CreationTime(), creationTime) < 0 Then
            oldestDir = dir
            creationTime = dir.CreationTime()
        End If
    Next

Upvotes: 1

Related Questions