Search code examples
c#directory-structure

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..


Solution

  • .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);
        }