Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have directory named Updates that inside has many folders named Update10, Update15,Update13 and so on. I need to be able to get the most recent update by comparing the numbers on the folder name and return the path to that folder. Any help would be aprecciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
260 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use LINQ:

int updateInt = 0;

var mostRecendUpdate = Directory.EnumerateDirectories(updateDir)
    .Select(path => new
    {
        fullPath = path,
        directoryName = System.IO.Path.GetFileName(path) // returns f.e. Update15
    })
    .Where(x => x.directoryName.StartsWith("Update"))    // precheck
    .Select(x => new
    {
        x.fullPath, x.directoryName,
        updStr = x.directoryName.Substring("Update".Length) // returns f.e. "15"
    })
    .Where(x => int.TryParse(x.updStr, out updateInt))      // int-check and initialization of updateInt
    .Select(x => new { x.fullPath, x.directoryName, update = updateInt })
    .OrderByDescending(x => x.update)                       // main task: sorting
    .FirstOrDefault();                                      // return newest update-infos

if(mostRecendUpdate != null)
{
    string fullPath = mostRecendUpdate.fullPath;
    int update = mostRecendUpdate.update;
}

A cleaner version uses a method that returns an int? instead of using the local variable as out-parameter because LINQ should not cause such side-effects. They could be harmful.

One note: currently the query is case sensitive, it won't recognize UPDATE11 as valid directory. If you want to compare case-insensitive you have to use the appropriate StartsWith overload:

.....
.Where(x => x.directoryName.StartsWith("Update", StringComparison.InvariantCultureIgnoreCase))    // precheck
.....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...