Reputation: 153
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!
Upvotes: 1
Views: 2868
Reputation: 30022
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");
Upvotes: 1
Reputation: 5312
In the OnChanged event:
private static void OnChanged(object source, FileSystemEventArgs e)
{
var currentTime = DateTime.Now;
var file = new FileInfo(e.FullPath);
var createdDateTime = file.CreationTime;
var span = createdDateTime.Subtract(currentTime);
if (span.Minutes > 30)
{
// your code
}
}
To filter on specific file extensions (such as pdf), you can use:
if (file.Extension == ".pdf")
{
}
Upvotes: 1