[Solved] Searching for the newest update in a directory c#


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

0

solved Searching for the newest update in a directory c#