Simple File System Watcher in C#

In this article I describe the usage of the FileSystemWatcher controller provided by .Net Framework , using C#


More information about FileSystemWatcher In C# is here..

Source Code :


  1. using System;
  2. using System.Text;
  3. using System.Security.Permissions;
  4. using System.IO;
  5. namespace FileSystemWatcherC
  6. {
  7.     class Program
  8.     {
  9.         static FileSystemWatcher watcher = null;
  10.         [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  11.         static void Main(string[] args)
  12.         {
  13.             Console.ForegroundColor = ConsoleColor.White;
  14.             Console.BackgroundColor = ConsoleColor.Black;
  15.             string[] argsx = System.Environment.GetCommandLineArgs();
  16.             Console.Title = "Egle Eye";
  17.             int len = argsx.Length;
  18.             /*
  19.              * Helper cordings...
  20.              *
  21.              * Console.WriteLine(len.ToString());            
  22.             foreach (string s in argsx)
  23.             {
  24.                 Console.Write(s + " ");
  25.             }
  26.              */
  27.             if (len < 2)
  28.             {
  29.                 DrawHelperScreen();
  30.             }
  31.             else
  32.             {
  33.                 try
  34.                 {
  35.                     watcher = new FileSystemWatcher();
  36.                     watcher.BeginInit();
  37.                     watcher.IncludeSubdirectories = true;
  38.                     SetFileTypes(string.Empty);
  39.                     SetArgs(argsx);
  40.                 }
  41.                 catch (Exception ex)
  42.                 {
  43.                     Console.ForegroundColor = ConsoleColor.Red;
  44.                     Console.BackgroundColor = ConsoleColor.Black;
  45.                     Console.WriteLine("");
  46.                     Console.WriteLine(ex.Message);
  47.                     Console.WriteLine("");
  48.                     Console.ForegroundColor = ConsoleColor.White;
  49.                     Console.BackgroundColor = ConsoleColor.Black;
  50.                     return;
  51.                 }
  52.             }
  53.         }
  54.         private static void SetWorkinfDirecotory(string path)
  55.         {
  56.             watcher.Path = path;
  57.         }
  58.         private static void SetArgs(string[] args)
  59.         {
  60.             if (args.Length > 1)
  61.             {
  62.                 SetWorkinfDirecotory(args[1]);
  63.             }
  64.             if (args.Length > 2)
  65.             {
  66.                 SetWachingEvents(args[2]);
  67.             }
  68.             else { SetWachingEvents(""); }
  69.             if (args.Length > 3)
  70.             {
  71.                 SetFileTypes(args[3]);
  72.             }
  73.             if (args.Length > 4)
  74.             {
  75.                 if (args[4].ToLower() == "false")
  76.                     watcher.IncludeSubdirectories = false;
  77.             }
  78.             /*
  79.              * Helper cordings...
  80.              *
  81.              * Console.WriteLine(watcher.Path);
  82.             Console.WriteLine(watcher.Filter);
  83.             Console.WriteLine(watcher.IncludeSubdirectories.ToString()); */
  84.             StartWatcher();
  85.         }
  86.         private static void SetWachingEvents(string filterEvents)
  87.         {
  88.             string[] values = filterEvents.Split(',');
  89.             foreach (string s in values)
  90.             {
  91.                 switch (s)
  92.                 {
  93.                     case "ch": watcher.Changed += new FileSystemEventHandler(OnChanged); break;
  94.                     case "cr": watcher.Created += new FileSystemEventHandler(OnChanged); break;
  95.                     case "de": watcher.Deleted += new FileSystemEventHandler(OnChanged); break;
  96.                     case "rn": watcher.Renamed += new RenamedEventHandler(OnRenamed); break;
  97.                     default:
  98.                         watcher.Changed += new FileSystemEventHandler(OnChanged);
  99.                         watcher.Created += new FileSystemEventHandler(OnChanged);
  100.                         watcher.Deleted += new FileSystemEventHandler(OnChanged);
  101.                         watcher.Renamed += new RenamedEventHandler(OnRenamed);
  102.                         break;
  103.                 }
  104.             }
  105.         }
  106.         private static void SetFileTypes(string filetypes)
  107.         {
  108.             if (filetypes != String.Empty)
  109.                 watcher.Filter = filetypes;
  110.             else watcher.Filter = "*.*";
  111.         }
  112.         private static void DrawHelperScreen()
  113.         {
  114.             //Console.Clear();
  115.             Console.ForegroundColor = ConsoleColor.DarkCyan;
  116.             Console.WriteLine("");
  117.             Console.WriteLine("");
  118.             Console.WriteLine(@"╔══════════════════════════Usage══════════════════════════╗");
  119.             Console.WriteLine("║                                                         ║");
  120.             Console.WriteLine(@"║    EgleEye [Waching directory]  - Ex C:\                ║");
  121.             Console.WriteLine("║                                                         ║");
  122.             Console.WriteLine(@"║    Filter: ch[Change],de[Delete],cr[Created],rn[Rename] ║");
  123.             Console.WriteLine("║    If no arguments with file path watch all events.     ║");
  124.             Console.WriteLine("║                                                         ║");
  125.             Console.WriteLine(@"║             EgleEye C:\ ch,de,cr,rn                     ║");
  126.             Console.WriteLine(@"║             EgleEye C:\ ch,de,cr                        ║");
  127.             Console.WriteLine(@"║             EgleEye C:\ ch,de                           ║");
  128.             Console.WriteLine(@"║             EgleEye C:\ ch                              ║");
  129.             Console.WriteLine(@"║             EgleEye C:\                                 ║");
  130.             Console.WriteLine("║                                                         ║");
  131.             Console.WriteLine(@"║    EgleEye [File Types *.* = all , *.txt = text ]       ║");
  132.             Console.WriteLine("║                                                         ║");
  133.             Console.WriteLine(@"║             File Types *recipe.doc                      ║");
  134.             Console.WriteLine(@"║             File Types *.txt                            ║");
  135.             Console.WriteLine(@"║             File Types pass*.*                          ║");
  136.             Console.WriteLine("║                                                         ║");
  137.             Console.WriteLine(@"║    Include Include Subdirectories for the search:off    ║");
  138.             Console.WriteLine("║                                                         ║");
  139.             Console.WriteLine(@"║             Subdirectories default ON                   ║");
  140.             Console.WriteLine(@"║             To desable it set args: false               ║");
  141.             Console.WriteLine("║                                                         ║");
  142.             Console.WriteLine(@"║             Usage :                                     ║");
  143.             Console.WriteLine(@"║             EgleEye C:\ ch,de,cr,rn *.* false           ║");
  144.             Console.WriteLine("║                                                         ║");
  145.             Console.WriteLine(@"║     **NOTE : To exit press 'q' and Hit Enter            ║");
  146.             Console.WriteLine("║                                                         ║");
  147.             Console.WriteLine(@"╚══════════════════════════Usage══════════════════════════╝");
  148.             return;
  149.         }
  150.         [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  151.         public static void StartWatcher()
  152.         {
  153.             watcher.NotifyFilter = NotifyFilters.LastAccess |
  154.                 NotifyFilters.LastWrite |
  155.                 NotifyFilters.FileName |
  156.                 NotifyFilters.DirectoryName |
  157.                 NotifyFilters.Attributes |
  158.                 NotifyFilters.Security;
  159.             watcher.EndInit();
  160.             watcher.EnableRaisingEvents = true;
  161.             Console.WriteLine("Press \'q\' and hit Enter to Exit.....");
  162.             while (Console.Read() != 'q') ;
  163.         }
  164.         private static void OnChanged(object source, FileSystemEventArgs e)
  165.         {
  166.             switch (e.ChangeType)
  167.             {
  168.                 case WatcherChangeTypes.Changed:
  169.                     Console.BackgroundColor = ConsoleColor.Black;
  170.                     Console.ForegroundColor = ConsoleColor.DarkGreen;
  171.                     break;
  172.                 case WatcherChangeTypes.Created:
  173.                     Console.BackgroundColor = ConsoleColor.Yellow;
  174.                     Console.ForegroundColor = ConsoleColor.Black;
  175.                     break;
  176.                 case WatcherChangeTypes.Deleted:
  177.                     Console.BackgroundColor = ConsoleColor.DarkRed;
  178.                     Console.ForegroundColor = ConsoleColor.Cyan;
  179.                     break;
  180.             }
  181.             WriteFullLine(e.ChangeType + " : " + e.FullPath, e);
  182.         }
  183.         private static void OnRenamed(object source, RenamedEventArgs e)
  184.         {
  185.             Console.ForegroundColor = ConsoleColor.DarkCyan;
  186.             Console.BackgroundColor = ConsoleColor.Black;
  187.             Console.WriteLine("");
  188.             Console.Write("Renamed :");
  189.             Console.WriteLine(" File Old : " + e.OldFullPath);
  190.             Console.WriteLine("          File New : " + e.FullPath);
  191.             Console.WriteLine("");
  192.         }
  193.         static void WriteFullLine(string value, FileSystemEventArgs e)
  194.         {
  195.             Console.WriteLine(value.PadRight(Console.WindowWidth - 1));
  196.         }
  197.     }
  198. }

Comments

Popular posts from this blog

Brother printer password reset using telnet

How to adjust the brightness in Samsung 19" SyncMaster SA100 LED monitor?

ASP.NET Server Controls Tutorial