What is the best method for finding the last last modified time in a file folder?

I have a folder with subfolders of files. I would like to get the latest modified time file name. Is there a more efficient way to find this so as not to loop through each folder and file to find it?

+3
source share
6 answers

depends on how you want to do this. Do you want you to run the software and then search for it or constantly run and track it?

in the latter case, it is useful to use the FileSystemWatcher class.

+3
source

Use an object FileSystemWatcher.

Dim folderToWatch As New FileSystemWatcher
folderToWatch.Path = "C:\FoldertoWatch\"
AddHandler folderToWatch.Created, AddressOf folderToWatch_Created
folderToWatch.EnableRaisingEvents = True
folderToWatch.IncludeSubdirectories = True
Console.ReadLine()

( folderToWatch_Created) - :

Console.WriteLine("File {0} was just created.", e.Name)
+2

FileSystemWatcher , , . . - ( ):

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);
+1

Linq, linq , . , , , , 4 . , .

+1

PowerShell,

dir -r | select Name, LastWriteTime | sort LastWriteTime -DESC | select -first 1

This way the script can work as needed, and you can pass the name (or full path) back to your system for processing.

0
source
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);
}
0
source

All Articles