Mikkel
Mikkel

Reputation: 133

Find out when file is added to folder

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

Answers (4)

PVitt
PVitt

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

XandrGuard
XandrGuard

Reputation: 141

For "snapshot" solution is possible to use this library https://github.com/igorcrevar/Directory-Snapshot-Difference-Csharp

Upvotes: 0

John Woo
John Woo

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.

Full Tutorial Here

It has events and theyare

  • Created - raised whenever a directory or file is created.
  • Deleted - raised whenever a directory or file is deleted.
  • Renamed - raised whenever the name of a directory or file is changed.
  • Changed - raised whenever changes are made to the size, system attributes, last write time, last access time or NTFS security permissions of a directory or file.

Upvotes: 4

Lloyd
Lloyd

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

Related Questions