1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | class WatchCurrentFolder { static FileSystemWatcher watcher = new FileSystemWatcher(); static void Main(string[] args) { watch(); } static void watch() { //watch current directory watcher.Path = Directory.GetCurrentDirectory(); //watch all types of files watcher.Filter = "*.*"; //watch for all types of activity watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.Security; //subscribe to the Created event watcher.Created += new FileSystemEventHandler(OnChanged); //start watching watcher.EnableRaisingEvents = true; // Wait for the user to quit the program. Console.WriteLine("Press \'q\' to quit"); while (Console.Read() != 'q') ; } private static void OnChanged(object sender, FileSystemEventArgs e) { try { //this is important: because OS operations take sometime //wait for OS operations to complete, else IOException System.Threading.Thread.Sleep(1000); //how to handle the event: e.g. read contents of affected file string contents = File.ReadAllText(e.FullPath); } catch (IOException ie) { Console.WriteLine("\t{0}", ie); } } } |
Sunday, 6 November 2016
Monitoring a Folder for New Files
One aspect of intrusion detection is to monitor critical folders for new files. I have found that it can be done through the following C# code.
Subscribe to:
Posts (Atom)