1 public class Watcher
2 {
3
4 public static void Main()
5 {
6
7 string[] args = System.Environment.GetCommandLineArgs();
8
9 // If a directory is not specified, exit program.
10 if (args.Length != 2)
11 {
12 // Display the proper way to call the program.
13 Console.WriteLine("Usage: Watcher.exe (directory)");
14 return;
15 }
16
17 // Create a new FileSystemWatcher and set its properties.
18 FileSystemWatcher watcher = new FileSystemWatcher();
19 watcher.Path = args[1];
20 /* Watch for changes in LastAccess and LastWrite times, and
21 the renaming of files or directories. */
22 watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
23 | NotifyFilters.FileName | NotifyFilters.DirectoryName;
24 // Only watch text files.
25 watcher.Filter = "*.txt";
26
27 // Add event handlers.
28 watcher.Changed += new FileSystemEventHandler(OnChanged);
29 watcher.Created += new FileSystemEventHandler(OnChanged);
30 watcher.Deleted += new FileSystemEventHandler(OnChanged);
31 watcher.Renamed += new RenamedEventHandler(OnRenamed);
32
33 // Begin watching.
34 watcher.EnableRaisingEvents = true;
35
36 // Wait for the user to quit the program.
37 Console.WriteLine("Press \'q\' to quit the sample.");
38 while (Console.Read() != 'q')
39 ;
40 }
41
42 // Define the event handlers.
43 private static void OnChanged(object source, FileSystemEventArgs e)
44 {
45 // Specify what is done when a file is changed, created, or deleted.
46 Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
47 }
48
49 private static void OnRenamed(object source, RenamedEventArgs e)
50 {
51 // Specify what is done when a file is renamed.
52 Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
53 }
54 }