Sunday, July 3, 2016

Show all folders inside a directory sorted by creation time.

Here's a solution using LINQ that will retrieve all folders inside a specific directory in order of creation time.
C#
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
string path = @"C:\";
if (Directory.Exists(path)) {
    DirectoryInfo dir = new DirectoryInfo(path);
    DirectoryInfo[] directories = dir.GetDirectories().
                                    OrderByDescending(p => p.CreationTime).
                                    ToArray();
    if (directories.Length > 0) {
        foreach (DirectoryInfo directory in directories) {
            ListBox1.Items.Add(directory.Name);
        }
    }
}

VB.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Dim path As String = "C:\"
If Directory.Exists(path) Then
    Dim dir As New DirectoryInfo(path)
    Dim directories As DirectoryInfo() = dir.GetDirectories().
                                             OrderByDescending(Function(p) p.CreationTime).
                                             ToArray()
    If directories.Length > 0 Then
        For Each directory As DirectoryInfo In directories
            ListBox1.Items.Add(directory.Name)
        Next
    End If
End If

0 comments:

Post a Comment