Ans:这是使用c#code
从文件夹中获取最新文件名的一种解决方案调用函数如下:
FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"D:\DatabaseFiles"));
功能:
public static FileInfo GetNewestFile(DirectoryInfo directory)
{
return directory.GetFiles()
.Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
.OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
.FirstOrDefault();
}
现在我的问题是有人请告诉我从文件夹中获取最新文件名的替代方法吗?
答案 0 :(得分:2)
为了找到列表中最大的项目而进行整个排序效率非常低。
您最好使用其中一个“MaxBy()”Linq扩展来查找最大值,例如MoreLinq one from Jon Skeet and others。 (完整的库是here。)
如果您使用MaxBy()
,代码可能如下所示:
public static FileInfo GetNewestFile(DirectoryInfo directory)
{
return directory.GetFiles()
.Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
.MaxBy(f => (f == null ? DateTime.MinValue : f.LastWriteTime));
}
理想情况下,您可以将此与其他建议的答案结合使用(即使用为您执行递归的Directory.EnumerateFiles()
重载。)
这是一个完整的控制台应用示例。 “MaxBy()”方法来源于旧版本的MoreLinq并进行了一些修改:
using System;
using System.Collections.Generic;
using System.IO;
namespace Demo
{
public static class Program
{
private static void Main()
{
string root = "D:\\Test"; // Put your test root here.
var di = new DirectoryInfo(root);
var newest = GetNewestFile(di);
Console.WriteLine("Newest file = {0}, last written on {1}", newest.FullName, newest.LastWriteTime);
}
public static FileInfo GetNewestFile(DirectoryInfo directory)
{
return directory.EnumerateFiles("*.*", SearchOption.AllDirectories)
.MaxBy(f => (f == null ? DateTime.MinValue : f.LastWriteTime));
}
}
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;
}
}
}
}
答案 1 :(得分:1)
您可以使用为您执行递归的override(其余代码来自您的问题)
return directory.GetFiles("*", SearchOption.AllDirectories)
.OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
.FirstOrDefault();
还有EnumerateFiles 可能更好(延期执行)
return directory.EnumerateFiles("*", SearchOption.AllDirectories)
.OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
.FirstOrDefault();