Home > Net >  How to get the first created folder instead the last?
How to get the first created folder instead the last?

Time:12-25

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 ?

CodePudding user response:

Change the OrderBy function, and the keySelector parameter:

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

CodePudding user response:

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);

CodePudding user response:

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();
}

CodePudding user response:

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();
  • Related