Find out when file is added to folder

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.


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.

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}");
}

Tags:

C#

File

Directory