using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace FileWatcher { class Program { static string directoryPath = @"C:\MyDir\"; static void Main(string[] args) { if (args.Length > 2) { Console.WriteLine("Useage: ConsoleApplication2 [WatchDir] [ArchiveDir]"); return; } else { // Make sure the directory location exists if (!Directory.Exists(directoryPath)) { Console.WriteLine("The directory '{0}' does not exist.", directoryPath); return; } } FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = directoryPath; // Specifying the filter types watcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime; watcher.Filter = "*.*"; // Register the event handlers watcher.Changed += new FileSystemEventHandler(watcher_Changed); watcher.Created += new FileSystemEventHandler(watcher_Created); watcher.Deleted += new FileSystemEventHandler(watcher_Changed); watcher.Renamed += new RenamedEventHandler(watcher_Renamed); // Enables the events watcher.EnableRaisingEvents = true; while (true) { System.Threading.Thread.Sleep(1000); } } /// <summary> /// Handles the Changed event of the watcher control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.IO.FileSystemEventArgs"/> instance containing the event data.</param> static void watcher_Changed(object sender, FileSystemEventArgs e) { Console.WriteLine("The file {0} has been changed", e.Name); } /// <summary> /// Handles the Created event of the watcher control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.IO.FileSystemEventArgs"/> instance containing the event data.</param> static void watcher_Created(object sender, FileSystemEventArgs e) { Console.WriteLine("A new file {0} is created", e.Name); } /// <summary> /// Handles the Renamed event of the watcher control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.IO.RenamedEventArgs"/> instance containing the event data.</param> static void watcher_Renamed(object sender, RenamedEventArgs e) { Console.WriteLine("The file {0} has been renamed", e.Name); } } }
|