Wednesday, 13 April 2011

How To Watch Directory using C#.NET

I have used a console based application in C# for watching my directory.
U can also use window based application for the same. Here is the code i have used for the console based application for watching any alteration in my directory.


****Inside the main function****
//Instance Of File Watcher Has Been Created
            FileSystemWatcher Watcher = new FileSystemWatcher();

            //Path To be watched by the watcher
            Watcher.Path = "G:\\Abhishek";

            //Filter files that are supposed to be watched
            Watcher.Filter = "*.*";

            //Specifying What To Look For Describing Attributes of the file system
            Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Attributes;

            //Specifies what need to be done if any of the attribute got altered
            Watcher.Changed += new FileSystemEventHandler(OnChanged);
            Watcher.Created += new FileSystemEventHandler(OnChanged);
            Watcher.Deleted += new FileSystemEventHandler(OnChanged);
            Watcher.Renamed += new RenamedEventHandler(OnRenamed);

            //Telling The watcher to do itz job WATCH IT!!!!
            Watcher.EnableRaisingEvents = true;

            //Keep the terminal alive
            Console.ReadLine();

****we have to create two more functions those we have called i.e OnChanged and OnRenamed****

        public  static void OnChanged(object sender, FileSystemEventArgs e)
        {
            switch (e.ChangeType)
            {
                case WatcherChangeTypes.Changed:
                    Console.WriteLine("File " + e.FullPath + " has been Modified");
                    break;
                case WatcherChangeTypes.Deleted:
                    Console.WriteLine("File " + e.FullPath + " has been Deleted");
                    break;
                case WatcherChangeTypes.Created:
                   Console.WriteLine("File " + e.FullPath + " has been Created");
                    break;
                default:
                    Console.WriteLine("Error Has Been Occured");
                    break;
            }

        }


        public static void OnRenamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine("File " + e.OldFullPath + " Renamed To " + e.FullPath);
        }
  • Remember one thing you have to make the functions as static