1 using System;
 2 using System.Threading;
 3  
 4 class DirectoryWatcher
 5 {
 6     public DirectoryWatcher(const string& directoryPath_) : exiting(false)directoryPath(directoryPath_)
 7     {
 8     }
 9     public void Start()
10     {
11         thread = Thread.StartMethod(Execute);
12     }
13     public void Stop()
14     {
15         exiting = true;
16         notifier.CancelWait();
17         thread.Join();
18     }
19     private void Execute()
20     {
21         try
22         {
23             notifier = System.Windows.IO.Directory.NotifyChanged(directoryPath);
24             while (!exiting)
25             {
26                 notifier.WaitAndCallWhenDirectoryChanged(DirectoryChanged);
27             }
28         }
29         catch (const Exception& ex)
30         {
31             Console.Error() << ex.ToString() << endl();
32         }
33     }
34     private void DirectoryChanged(const string& directoryPath)
35     {
36         Console.WriteLine("directory '" + directoryPath + "' changed");
37     }
38     private string directoryPath;
39     private System.Windows.IO.DirectoryChangeNotifier notifier;
40     private Thread thread;
41     private bool exiting;
42 }
43 
44 int main()
45 {
46     try
47     {
48         Console.WriteLine("begin watching 'D:/temp/watchThisDir'... (press enter to exit)");
49         DirectoryWatcher watcher("D:/temp/watchThisDir");
50         watcher.Start();
51         Console.ReadLine();
52         watcher.Stop();
53         Console.WriteLine("exiting.");
54     }
55     catch (const Exception& ex)
56     {
57         Console.Error() << ex.ToString() << endl();
58         return 1;
59     }
60     return 0;
61 }