Reputation: 133
I would like to know if it is possible to find out when a file is added to a folder in C#. I know you can see the time of creation and many other things in the FileInfo, but nok when it was added.
Upvotes: 12
Views: 12967
Reputation: 11770
You can use the System.IO.FileSystemWatcher. It provides methods to do exactly what you want to do:
FileSystemWatcher watcher = new FileSystemWatcher()
{
Path = stringWithYourPath,
Filter = "*.txt"
};
// Add event handlers for all events you want to handle
watcher.Created += new FileSystemEventHandler(OnChanged);
// Activate the watcher
watcher.EnableRaisingEvents = true
Where OnChanged is an event handler:
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
}
Upvotes: 17
Reputation: 141
For "snapshot" solution is possible to use this library https://github.com/igorcrevar/Directory-Snapshot-Difference-Csharp
Upvotes: 0
Reputation: 263943
FileSystemWatcher is a very powerful component, which allows us to connect to the directories and watch for specific changes within them, such as creation of new files, addition of subdirectories and renaming of files or subdirectories. This makes it possible to easily detect when certain files or directories are created, modified or deleted. It is one of the members of System.IO namespace.
It has events and theyare
Upvotes: 4
Reputation: 29678
Check out the FileSystemWatcher class - http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx
You'll find a complete example towards the bottom of the page.
Upvotes: 8