Anyname Donotcare Anyname Donotcare - 1 year ago 55
ASP.NET (C#) Question

How to get the names of the last child directory in list

How to get the name of the last folder.
I try something like this:

var directories = Directory.GetDirectories("D:\\" + new DateTime(2016, 11, 2).ToString("d-MM-yyyy"))
.ForEach(a => a.Split('/')[1]);

Answer Source

Use .Last:

var fullName = Directory.GetDirectories("C:\\").Last();
var folderName = fullName.Substring(fullName.LastIndexOf('\\')+1);

Or OrderByDescending:

var fullName = Directory.GetDirectories("C:\\")
                        .OrderByDescending(directory => /* some predicate */)
if(fullName != null)
    var folderName = fullName.Substring(fullName.LastIndexOf('\\')+1);

For .Last too you can give a predicate

Putting it into your code, use .Select instead of ForEach and chain the next function:

var lastDirectory = Directory
                        .GetDirectories("D:\\" + new DateTime(2016, 11, 2).ToString("d-MM-yyyy"))
                        .Select(directory => directory.Substring(directory.LastIndexOf('\\')+1))

To search in all nested directories use a different overload of GetDirectories which specifies the SearchOptions:

Directory.GetDirectories("path", "pattern", SearchOption.AllDirectories)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download