Get latest directory in a path - with respect to the the name of directory RRS feed

  • Question

  • Hi, i have a requirement to get the last created directory in a path with respect to its name, as an application i use created 2 directories during the runtime and i need to consider only one of them, which in order appears later. For e.g the app creates 2 folders with name: 60000c and b3c143 and i need the one with the name "b3c143". How can i acheive this? Thanks.
    Friday, February 22, 2019 8:46 AM

All replies

  • By LINQ:

    string olderDirectory = Directory.GetDirectories(pathToDirectory).OrderBy(k=>new DirectoryInfo(k).CreationTime).First();

    Friday, February 22, 2019 10:40 AM
  • In order to get the last directory, try this too:

    string newest_directory = new DirectoryInfo( path ).EnumerateDirectories().OrderByDescending( d => d.CreationTime ).FirstOrDefault()?.FullName;

    Friday, February 22, 2019 12:26 PM
  • Hello,

    Viorel_ and Petr B are doing the exact same thing but Viorel_ code sample uses FirstOrDefault which is best while Petr B uses First which is no a good idea as if there are no folders by chance an exception is thrown. But even with FirstOrDefault a null check is in order.

    var somePath = @"C:\OED\bootstrap";
    var newestDirectory = new DirectoryInfo(somePath)
        .OrderByDescending(d => d.CreationTime).FirstOrDefault()?.FullName;
    if (newestDirectory != null)
        // we have the folder
        // folder has no sub folders

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, February 22, 2019 3:14 PM
  • Hi 

    Is your problem solved? If so, please post "Mark as answer" to the appropriate answer, so that it will help other members to find a solution quickly if they face a similar issue.

    Best Regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Monday, February 25, 2019 6:06 AM