Willcode4cash

FileSystemWatcher example

Aug 14th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Security.Permissions;
  4.  
  5. public class Watcher
  6. {
  7.  
  8.     public static void Main()
  9.     {
  10.     Run();
  11.  
  12.     }
  13.  
  14.     [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
  15.     public static void Run()
  16.     {
  17.         string[] args = System.Environment.GetCommandLineArgs();
  18.  
  19.         // If a directory is not specified, exit program.
  20.         if(args.Length != 2)
  21.         {
  22.             // Display the proper way to call the program.
  23.             Console.WriteLine("Usage: Watcher.exe (directory)");
  24.             return;
  25.         }
  26.  
  27.         // Create a new FileSystemWatcher and set its properties.
  28.         FileSystemWatcher watcher = new FileSystemWatcher();
  29.         watcher.Path = args[1];
  30.         /* Watch for changes in LastAccess and LastWrite times, and
  31.            the renaming of files or directories. */
  32.         watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
  33.            | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  34.         // Only watch text files.
  35.         watcher.Filter = "*.txt";
  36.  
  37.         // Add event handlers.
  38.         watcher.Changed += new FileSystemEventHandler(OnChanged);
  39.         watcher.Created += new FileSystemEventHandler(OnChanged);
  40.         watcher.Deleted += new FileSystemEventHandler(OnChanged);
  41.         watcher.Renamed += new RenamedEventHandler(OnRenamed);
  42.  
  43.         // Begin watching.
  44.         watcher.EnableRaisingEvents = true;
  45.  
  46.         // Wait for the user to quit the program.
  47.         Console.WriteLine("Press \'q\' to quit the sample.");
  48.         while(Console.Read()!='q');
  49.     }
  50.  
  51.     // Define the event handlers.
  52.     private static void OnChanged(object source, FileSystemEventArgs e)
  53.     {
  54.         // Specify what is done when a file is changed, created, or deleted.
  55.        Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
  56.     }
  57.  
  58.     private static void OnRenamed(object source, RenamedEventArgs e)
  59.     {
  60.         // Specify what is done when a file is renamed.
  61.         Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
  62.     }
  63. }
Add Comment
Please, Sign In to add comment