Anyname Donotcare Anyname Donotcare - 1 month ago 5
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"))
.ToList()
.ForEach(a => a.Split('/')[1]);

Answer

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 */)
                        .FirstOrDefault();
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))
                        .Last();

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

Directory.GetDirectories("path", "pattern", SearchOption.AllDirectories)
Comments