如何使用.NET 在不循环的情况下查找目录中的最新文件?

我需要在一个目录中找到最近修改过的文件。

我知道我可以循环遍历文件夹中的每个文件并比较 File.GetLastWriteTime,但是有没有更好的方法不用循环?.

232250 次浏览

您可以使用 FileSystemWatcher 文件系统监视器对新的文件活动作出反应。

这样如何..。

var directory = new DirectoryInfo("C:\\MyDirectory");
var myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();


// or...
var myFile = directory.GetFiles()
.OrderByDescending(f => f.LastWriteTime)
.First();

非 LINQ 版本:

/// <summary>
/// Returns latest writen file from the specified directory.
/// If the directory does not exist or doesn't contain any file, DateTime.MinValue is returned.
/// </summary>
/// <param name="directoryInfo">Path of the directory that needs to be scanned</param>
/// <returns></returns>
private static DateTime GetLatestWriteTimeFromFileInDirectory(DirectoryInfo directoryInfo)
{
if (directoryInfo == null || !directoryInfo.Exists)
return DateTime.MinValue;


FileInfo[] files = directoryInfo.GetFiles();
DateTime lastWrite = DateTime.MinValue;


foreach (FileInfo file in files)
{
if (file.LastWriteTime > lastWrite)
{
lastWrite = file.LastWriteTime;
}
}


return lastWrite;
}


/// <summary>
/// Returns file's latest writen timestamp from the specified directory.
/// If the directory does not exist or doesn't contain any file, null is returned.
/// </summary>
/// <param name="directoryInfo">Path of the directory that needs to be scanned</param>
/// <returns></returns>
private static FileInfo GetLatestWritenFileFileInDirectory(DirectoryInfo directoryInfo)
{
if (directoryInfo == null || !directoryInfo.Exists)
return null;


FileInfo[] files = directoryInfo.GetFiles();
DateTime lastWrite = DateTime.MinValue;
FileInfo lastWritenFile = null;


foreach (FileInfo file in files)
{
if (file.LastWriteTime > lastWrite)
{
lastWrite = file.LastWriteTime;
lastWritenFile = file;
}
}
return lastWritenFile;
}

如果你想要递归搜索,你可以使用这段漂亮的代码:

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();
}

这么说吧:

FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"C:\directory\"));

如果目录为空,返回一个 FileInfo实例或者 null

private List<FileInfo> GetLastUpdatedFileInDirectory(DirectoryInfo directoryInfo)
{
FileInfo[] files = directoryInfo.GetFiles();
List<FileInfo> lastUpdatedFile = null;
DateTime lastUpdate = new DateTime(1, 0, 0);
foreach (FileInfo file in files)
{
if (file.LastAccessTime > lastUpdate)
{
lastUpdatedFile.Add(file);
lastUpdate = file.LastAccessTime;
}
}


return lastUpdatedFile;
}

展开上面的第一个,如果你想搜索一个特定的模式,你可以使用以下代码:

using System.IO;
using System.Linq;
...
string pattern = "*.txt";
var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();

下面是从每个子目录获取最新文件的版本

List<string> reports = new List<string>();
DirectoryInfo directory = new DirectoryInfo(ReportsRoot);
directory.GetFiles("*.xlsx", SearchOption.AllDirectories).GroupBy(fl => fl.DirectoryName)
.ForEach(g => reports.Add(g.OrderByDescending(fi => fi.LastWriteTime).First().FullName));

有点晚了,但是..。

你的代码将不工作,因为 list<FileInfo> lastUpdateFile = null; 然后是 lastUpdatedFile.Add(file);,因此将引发 NullReference 异常。 工作版本应该是:

private List<FileInfo> GetLastUpdatedFileInDirectory(DirectoryInfo directoryInfo)
{
FileInfo[] files = directoryInfo.GetFiles();
List<FileInfo> lastUpdatedFile = new List<FileInfo>();
DateTime lastUpdate = DateTime.MinValue;
foreach (FileInfo file in files)
{
if (file.LastAccessTime > lastUpdate)
{
lastUpdatedFile.Add(file);
lastUpdate = file.LastAccessTime;
}
}


return lastUpdatedFile;
}

谢谢

这是我的一些应用程序,我使用这样的声明:

  var inputDirectory = new DirectoryInfo("\\Directory_Path_here");
var myFile = inputDirectory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();

从这里开始,您将获得“ inputDirectory”变量的 Directory 中最近保存/添加/更新的文件的文件名。现在你可以访问它,做你想做的。

希望能帮上忙。

简明扼要 :

new DirectoryInfo(path).GetFiles().OrderByDescending(o => o.LastWriteTime).FirstOrDefault();

另一种方法,如果您正在使用 Directory.EnumerateFiles,并且希望读取最新修改的文件。

foreach (string file in Directory.EnumerateFiles(fileDirectory, fileType).OrderByDescending(f => new FileInfo(f).LastWriteTime))


}