Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: what is the simplest way to sort the directory names and pick the most recent one?

I have a list of directories in a parent directory. These directories will be created in a format like 00001, 00002, 00003... so that the one with the bigger trailing number is the recent one. in the above instance, it is 00003. I want to get this programmatically.

thanks for any help..

like image 479
satya Avatar asked Jan 19 '10 11:01

satya


2 Answers

Try this:

var first = Directory.GetDirectories(@"C:\")
   .OrderByDescending(x => x).FirstOrDefault();

Obviously replace C:\ with the path of the parent directory.

like image 94
RichardOD Avatar answered Nov 12 '22 14:11

RichardOD


.NET 2:

    private void button1_Click(object sender, EventArgs e) {
        DirectoryInfo di = new DirectoryInfo(@"C:\Windows");
        DirectoryInfo[] dirs = di.GetDirectories("*", 
            SearchOption.TopDirectoryOnly);

        Array.Sort<DirectoryInfo>(dirs, 
            new Comparison<DirectoryInfo>(CompareDirs);
    }

    int CompareDirs(DirectoryInfo a, DirectoryInfo b) {
        return a.CreationTime.CompareTo(b.CreationTime);
    }
like image 25
serhio Avatar answered Nov 12 '22 13:11

serhio