PassThePeas
7/3/2017 - 5:16 PM

Watching a folder

Watching a folder

using System.IO;
// Watches the C:\Temp folder and notifies creation of new text files
public static void WatchTempFolder()
{
    // Create the FileSystemoFileSystemWatcher object and set its properties
    FileSystemWatcher oFileSystemWatcher = new FileSystemWatcher();
    oFileSystemWatcher.Path = "C:\\Temp";
    oFileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess 
          | NotifyFilters.LastWrite | NotifyFilters.FileName | 
            NotifyFilters.DirectoryName;
    oFileSystemWatcher.Filter = "*.txt";

    // Add event handlers.
    oFileSystemWatcher.Created += new FileSystemEventHandler(OnCreated);

    // Begin watching.
    oFileSystemWatcher.EnableRaisingEvents = true;

    // Wait for the user to quit the program.
    Console.WriteLine("Press \'q\' to quit the sample.");
    while(Console.Read()!='q');
}

// The event handler
private static void OnCreated(object source, FileSystemEventArgs e)
{
    Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
}