Von Justine Napalang
Von Justine Napalang

Reputation: 67

How to find the date time of the most recent file

I'm trying to make a console app running in background and check if there's no new files created within an hour. Now I'm facing the problem how to get the time of the most recent file in a folder.

Here's what i have tried:

string path1 = @"C:\Users\nx011116\Documents\test folder\server";
string[] subdir1 = Directory.GetDirectories(path1);
for (int a = 0; a < subdir1.Length; a++)
{
    var directory = new DirectoryInfo(subdir1[a]);
    var myFile = directory.GetFiles()
       .OrderByDescending(f => f.LastWriteTime)
       .First();

    Console.WriteLine(myFile);
}

As a result I'm getting the last file in the folder. Is this console app running in the background?

Now I'm able to get the DateTime of the most recent file in the folder. But how can I find if there's no new files in the folder within an hour?

Updated Code

string path1 = @"C:\Users\nx011116\Documents\test folder\server";
string[] subdir1 = Directory.GetDirectories(path1);
for (int a = 0; a < subdir1.Length; a++)
{
    var directory = new DirectoryInfo(subdir1[a]);
    var myFile = directory.GetFiles()
        .OrderByDescending(f => f.LastWriteTime)
        .First();

    Console.WriteLine(myFile.LastAccessTime.ToString());
}

Upvotes: 0

Views: 246

Answers (2)

tmaj
tmaj

Reputation: 34967

System.IO.FileSystemWatcher

public static async Task Main(string[] args)
{
    string dir = @"C:\tmp";

    var watcher = new System.IO.FileSystemWatcher();
    watcher.Path = dir;
    //watcher.NotifyFilter = ; //Add filters if desired
    watcher.Filter = "*.*";
    watcher.Changed += 
       (source, e) =>  Console.WriteLine($"{DateTime.UtcNow}: {e.ChangeType} {e.FullPath}");
    watcher.Created +=
      (source, e) => Console.WriteLine($"{DateTime.UtcNow}: {e.ChangeType} {e.FullPath}");
    watcher.EnableRaisingEvents = true;

    Console.ReadLine();
}

Example output

15/10/2019 00:49:24: Created C:\tmp\New Text Document.txt
15/10/2019 00:49:30: Changed C:\tmp\New Text Document.txt
15/10/2019 00:49:30: Changed C:\tmp\New Text Document.txt


Directory.GetLastWriteTimeUtc

If you just want to detect if there are new files in the top directory (no in subdirectories) you can use Directory.GetLastWriteTimeUtc(String).

Please note the note though:

This method may return an inaccurate value, because it uses native functions whose values may not be continuously updated by the operating system.


Naive

For completeness here is a very explicit disk heavy naive solution.

string dir = @"C:\tmp";

while (true)
{
    Console.WriteLine($"");

    var desiredSinceUtc = DateTime.UtcNow.AddSeconds(-5);

    var files = System.IO.Directory.EnumerateFiles(dir, "*", System.IO.SearchOption.AllDirectories);
    var freshFiles = files.Where(f => System.IO.File.GetLastWriteTimeUtc(f) > desiredSinceUtc);

    foreach ( var f in freshFiles )
    {
        Console.WriteLine($"\t{f}");
    }
    await Task.Delay(TimeSpan.FromSeconds(5));
}

Upvotes: 2

Xihuny
Xihuny

Reputation: 1538

A simple solution would be to count the total number of files and store it in a variable. Next time, check whether the total number of files is greater than the previous total count value. If it is equal, it means there is no new file.

Upvotes: 1

Related Questions