在目录 c# 中搜索最新更新
Searching for the newest update in a directory c#
我有一个名为 Updates 的目录,里面有许多名为 Update10、Update15、Update13 等的文件夹。
我需要能够通过比较文件夹名称上的数字和 return 该文件夹的路径来获取最新更新。
如有任何帮助,我们将不胜感激
您可以使用 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 使用 returns 和 int?
的方法而不是使用局部变量作为输出参数,因为 LINQ 不应导致此类副作用。它们可能有害。
请注意:目前查询区分大小写,它不会将 UPDATE11
识别为有效目录。如果你想比较不区分大小写,你必须使用适当的 StartsWith
重载:
.....
.Where(x => x.directoryName.StartsWith("Update", StringComparison.InvariantCultureIgnoreCase)) // precheck
.....
最好的方法是按照相关评论的建议使用修改日期。
然而,要将字符串作为数字排序,您可以使用 IComparer。
这已经完成,可以在 here
中找到
用样本编辑
获得目录后:
string[] dirs = System.IO.Directory.GetDirectories();
var numComp = new NumericComparer();
Array.Sort(dirs, numComp);
目录中的最后一项 是您的最后一个 "modified" 目录。
该函数使用LINQ获取上次更新目录路径。
public string GetLatestUpdate(string path)
{
if (!path.EndsWith("\")) path += "\";
return System.IO.Directory.GetDirectories(path)
.Select(f => new KeyValuePair<string, long>(f, long.Parse(f.Remove(0, (path + "Update").Length))))
.OrderByDescending(kvp => kvp.Value)
.First().Key;
}
如果您可以依赖文件夹的创建日期,您可以使用 MoreLinq's MaxBy()
:
来简化这一过程
string updatesFolder = "D:\TEST\Updates"; // Your path goes here.
var newest = Directory.EnumerateDirectories(updatesFolder, "Update*")
.MaxBy(folder => new DirectoryInfo(folder).CreationTime);
作为参考,MaxBy()
的一个实现是:
public static class EnumerableMaxMinExt
{
public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
{
return source.MaxBy(selector, Comparer<TKey>.Default);
}
public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer)
{
using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
{
throw new InvalidOperationException("Sequence was empty");
}
TSource max = sourceIterator.Current;
TKey maxKey = selector(max);
while (sourceIterator.MoveNext())
{
TSource candidate = sourceIterator.Current;
TKey candidateProjected = selector(candidate);
if (comparer.Compare(candidateProjected, maxKey) > 0)
{
max = candidate;
maxKey = candidateProjected;
}
}
return max;
}
}
}
我有一个名为 Updates 的目录,里面有许多名为 Update10、Update15、Update13 等的文件夹。 我需要能够通过比较文件夹名称上的数字和 return 该文件夹的路径来获取最新更新。 如有任何帮助,我们将不胜感激
您可以使用 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 使用 returns 和 int?
的方法而不是使用局部变量作为输出参数,因为 LINQ 不应导致此类副作用。它们可能有害。
请注意:目前查询区分大小写,它不会将 UPDATE11
识别为有效目录。如果你想比较不区分大小写,你必须使用适当的 StartsWith
重载:
.....
.Where(x => x.directoryName.StartsWith("Update", StringComparison.InvariantCultureIgnoreCase)) // precheck
.....
最好的方法是按照相关评论的建议使用修改日期。 然而,要将字符串作为数字排序,您可以使用 IComparer。 这已经完成,可以在 here
中找到用样本编辑
获得目录后:
string[] dirs = System.IO.Directory.GetDirectories();
var numComp = new NumericComparer();
Array.Sort(dirs, numComp);
目录中的最后一项 是您的最后一个 "modified" 目录。
该函数使用LINQ获取上次更新目录路径。
public string GetLatestUpdate(string path)
{
if (!path.EndsWith("\")) path += "\";
return System.IO.Directory.GetDirectories(path)
.Select(f => new KeyValuePair<string, long>(f, long.Parse(f.Remove(0, (path + "Update").Length))))
.OrderByDescending(kvp => kvp.Value)
.First().Key;
}
如果您可以依赖文件夹的创建日期,您可以使用 MoreLinq's MaxBy()
:
string updatesFolder = "D:\TEST\Updates"; // Your path goes here.
var newest = Directory.EnumerateDirectories(updatesFolder, "Update*")
.MaxBy(folder => new DirectoryInfo(folder).CreationTime);
作为参考,MaxBy()
的一个实现是:
public static class EnumerableMaxMinExt
{
public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
{
return source.MaxBy(selector, Comparer<TKey>.Default);
}
public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer)
{
using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
{
throw new InvalidOperationException("Sequence was empty");
}
TSource max = sourceIterator.Current;
TKey maxKey = selector(max);
while (sourceIterator.MoveNext())
{
TSource candidate = sourceIterator.Current;
TKey candidateProjected = selector(candidate);
if (comparer.Compare(candidateProjected, maxKey) > 0)
{
max = candidate;
maxKey = candidateProjected;
}
}
return max;
}
}
}