How to get the first created folder instead the last?

65 Views Asked by At
var lastWrittenFolder = new DirectoryInfo(textBoxPath.Text).GetDirectories()
                       .OrderByDescending(d => d.LastWriteTimeUtc).First();

this is working fine for getting the latest created folder.

but how do i get the first created folder ?

4

There are 4 best solutions below

0
Benny Shtemer On BEST ANSWER

Change the OrderBy function, and the keySelector parameter:

var lastWrittenFolder = new DirectoryInfo(textBoxPath.Text).GetDirectories()
                   .OrderBy(d => d.CreationTimeUtc).First();
2
Daya On

following code will help you.

static void Main()
{
    var folderPath = "your-folder-path";

    var directories = new DirectoryInfo(folderPath).GetDirectories();

    foreach (var item in directories.OrderBy(m => m.LastWriteTime))
    {
        Console.WriteLine(item.LastWriteTime + " " + item.Name);
    }


    Console.ReadLine();
}
0
Vivek Nuna On

You can also use Min, so you need the record which has the minimum creation date.

var firstCreatedFolder = new DirectoryInfo(textBoxPath.Text).GetDirectories()
                       .Min(d => d.CreationTimeUtc);
0
Eliano On

You are already there. Just instead of sorting the folder in reverse order ( bottom to top) just sort them from top to bottom and then select the first one like you did.

Here is correct code :

var lastWrittenFolder = new DirectoryInfo(path).GetDirectories().OrderBy(d => d.LastWriteTimeUtc).First();