C# 如何使用 .NET 在目录中查找最新的文件,并且不循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1179970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the most recent file in a directory using .NET, and without looping?
提问by Chris Klepeis
I need to find the most recently modified file in a directory.
我需要在目录中找到最近修改的文件。
I know I can loop through every file in a folder and compare File.GetLastWriteTime
, but is there a better way to do this without looping?.
我知道我可以遍历文件夹中的每个文件并比较File.GetLastWriteTime
,但是有没有更好的方法来做到这一点而不循环?
采纳答案by Scott Ivey
how about something like this...
这样的事情怎么样...
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();
回答by Scott Marlowe
You can react to new file activity with FileSystemWatcher.
您可以使用FileSystemWatcher对新文件活动做出反应。
回答by TimothyP
A non-LINQ version:
非 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;
}
回答by Edgar Villegas Alvarado
If you want to search recursively, you can use this beautiful piece of code:
如果你想递归搜索,你可以使用这段漂亮的代码:
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();
}
Just call it the following way:
只需按以下方式调用它:
FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"C:\directory\"));
and that's it. Returns a FileInfo
instance or null
if the directory is empty.
就是这样。返回一个FileInfo
实例或null
目录是否为空。
回答by Sylver1981
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;
}
回答by Zamir
Expanding on the first one above, if you want to search for a certain pattern you may use the following code:
扩展上面的第一个,如果您想搜索某个模式,您可以使用以下代码:
string pattern = "*.txt";
var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();
回答by Michael Bahig
Here's a version that gets the most recent file from each subdirectory
这是一个从每个子目录中获取最新文件的版本
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));
回答by Oleg Karbushev
it's a bit late but...
有点晚了但是...
your code will not work, because of list<FileInfo> lastUpdateFile = null;
and later lastUpdatedFile.Add(file);
so NullReference exception will be thrown.
Working version should be:
您的代码将无法工作,因为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;
}
Thanks
谢谢
回答by JasonR
I do this is a bunch of my apps and I use a statement like this:
我这样做是我的一堆应用程序,我使用这样的语句:
var inputDirectory = new DirectoryInfo("\Directory_Path_here");
var myFile = inputDirectory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();
From here you will have the filename for the most recently saved/added/updated file in the Directory of the "inputDirectory" variable. Now you can access it and do what you want with it.
从这里,您将在“inputDirectory”变量的目录中获得最近保存/添加/更新的文件的文件名。现在您可以访问它并使用它做您想做的事情。
Hope that helps.
希望有帮助。
回答by Jacob
Short and simple:
简短而简单:
new DirectoryInfo(path).GetFiles().OrderByDescending(o => o.LastWriteTime).FirstOrDefault();