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?.
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?.
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();
directory.GetFiles().OrderByDescending(f => f.LastWriteTime).First()
–
Its FirstOrDefault()
instead of First()
? The latter will cause an InvalidOperationException
if the directory is empty. –
Miskolc Expanding on the first one above, if you want to search for a certain pattern you may use the following code:
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();
using System.Linq
or else there will be an error. –
Rusty 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.
A non-LINQ version:
/// <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;
}
Short and simple:
new DirectoryInfo(path).GetFiles().OrderByDescending(o => o.LastWriteTime).FirstOrDefault();
Another approach if you are using Directory.EnumerateFiles
and want to read files in latest modified by first.
foreach (string file in Directory.EnumerateFiles(fileDirectory, fileType).OrderByDescending(f => new FileInfo(f).LastWriteTime))
}
You can react to new file activity with FileSystemWatcher.
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:
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
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));
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;
}
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.
Hope that helps.
© 2022 - 2025 — McMap. All rights reserved.