I have a folder with subfolders of files. I would like to get the newest filename by modified time. Is there a more efficient way of finding this short of looping through each folder and file to find it?
views:
615answers:
6depends on how you want to do it. do you want you software to start and then look for it or continuously run and keep track of it?
in the last case its good to make use of the FileSystemWatcher class.
If you have PowerShell installed, the command would be
dir -r | select Name, LastWriteTime | sort LastWriteTime -DESC | select -first 1
This way, the script could run as necessary and you could pass the Name (or full path) back into your system for processing.
Use the FileSystemWatcher object.
Dim folderToWatch As New FileSystemWatcher folderToWatch.Path = "C:\FoldertoWatch\" AddHandler folderToWatch.Created, AddressOf folderToWatch_Created folderToWatch.EnableRaisingEvents = True folderToWatch.IncludeSubdirectories = True Console.ReadLine()
Then, just create a handler (here called folderToWatch_Created) and do something like:
Console.WriteLine("File {0} was just created.", e.Name)
Using FileSystemWatcher will work assuming you only need to know this information after the app is loaded. Otherwise you still need to loop. Something like this would work (and doesn't use recursion):
Stack<DirectoryInfo> dirs = new Stack<DirectoryInfo>();
FileInfo mostRecent = null;
dirs.Push(new DirectoryInfo("C:\\TEMP"));
while (dirs.Count > 0) {
DirectoryInfo current = dirs.Pop();
Array.ForEach(current.GetFiles(), delegate(FileInfo f)
{
if (mostRecent == null || mostRecent.LastWriteTime < f.LastWriteTime)
mostRecent = f;
});
Array.ForEach(current.GetDirectories(), delegate(DirectoryInfo d)
{
dirs.Push(d);
});
}
Console.Write("Most recent: {0}", mostRecent.FullName);
If you like Linq you could use linq to object to query your filesystem the way you want. A sample is given here, you can play around and get what you want in probably 4 lines of code. Make sure your app has proper access rights to the folders.
void Main()
{
string startDirectory = @"c:\temp";
var dir = new DirectoryInfo(startDirectory);
FileInfo mostRecentlyEditedFile =
(from file in dir.GetFiles("*.*", SearchOption.AllDirectories)
orderby file.LastWriteTime descending
select file).ToList().First();
Console.Write(@"{0}\{1}",
mostRecentlyEditedFile.DirectoryName,
mostRecentlyEditedFile.Name);
}