Search code examples
c#directoryfilesystemwatcherdatecreated

Look for file in folder, get & compare latest date created in c#


I need monitor a folder, see if a file or files has been uploaded. And then I need to get the created date & time of the latest file that has been uploaded and see whether the time creation of the file has been more than 30 minutes from the current time. I have used the FileSystemWatcher to monitor the folder but how should I proceed for finding and comparing the latest file with current time.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  NotifyFilters.DirectoryName;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

Private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory.
}

How shall I do that in c#. Please help!


Solution

  • From your comments, i can't really see why you need to use FileSystemWatcher. You say you have a scheduled task every 1 hour that needs to check a directory for creation time of files. So in that task, just do the below:

    // Change @"C:\" to your upload directory
    string[] files = Directory.GetFiles(@"C:\");
    
    var oldestFile = files.OrderBy(path => File.GetCreationTime(path)).FirstOrDefault();
    if (oldestFile != null)
    {
        var oldestDate = File.GetCreationTime(oldestFile);
    
        if (DateTime.Now.Subtract(oldestDate).TotalMinutes > 30)
        {
            // Do Something
        }
    }
    

    To Filter specific files, use the overload :

    string[] files = Directory.GetFiles(@"C:\", "*.pdf");