views:

319

answers:

5

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

+4  A: 

Try this:

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

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

RichardOD
thanks RichardOD. Its my mistake. Removed my above comment..
satya
@rainbow365- no worries. I just wasn't sure what the issue could of been!
RichardOD
+2  A: 

Why not do something like this:

string[] directories = Directory.GetDirectories(@"C:\temp");
string lastDirectory = string.Empty;

if (directories.Length > 0)
{
    Array.Sort(directories);
    lastDirectory = directories[directories.Length - 1];
}
Wim Haanstra
+1  A: 

.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);
    }
serhio
A: 

What about:

var greaterDirectory =
    Directory.GetDirectories(@"C:\")
        .Select(path => Path.GetFileName(path)) // keeps only directory name
        .Max();

or

var simplest = Directory.GetDirectories(@"C:\").Max();
Rubens Farias
Isn't that doing twice the work - ordering into ascending order and then walking the collection again to get the Maximum value?
JBRWilkinson
@JBRWilkinson, you were right, fixed
Rubens Farias