在目录C#中搜索最新更新 [英] Searching for the newest update in a directory c#

查看:51
本文介绍了在目录C#中搜索最新更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Updates的目录,该目录中有许多名为Update10,Update15,Update13等的文件夹. 我需要能够通过比较文件夹名称上的数字并获取该文件夹的路径来获取最新的更新. 任何帮助将不胜感激

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

推荐答案

您可以使用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;
}

一个更清洁的版本使用的是一种返回int?的方法,而不是使用局部变量作为输出参数,因为LINQ不应引起此类副作用.它们可能有害.

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.

一个注意事项:当前查询区分大小写,它不会将UPDATE11识别为有效目录.如果要比较不区分大小写的字母,则必须使用适当的StartsWith重载:

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

这篇关于在目录C#中搜索最新更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆