Search code examples
c#loggingwindows-servicesfilesystemwatcher

Waiting while FileSystemWatcher is monitoring directory


I am trying to monitor a log file for changes. My code is working, and does everything it should. However, as I want this to run as a windows service and be constantly monitoring I'm not sure of the proper way to set it into a waiting state. Here is what it's doing at the moment.

    public static void Main()
    {
            log_watcher = new FileSystemWatcher();
            log_watcher.Path = Path.GetDirectoryName(pathToFile);
            log_watcher.Filter = recent_file.Name;
            log_watcher.NotifyFilter = NotifyFilters.LastWrite;
            log_watcher.Changed += new FileSystemEventHandler(OnChanged);

            log_watcher.EnableRaisingEvents = true;
            //do rest of stuff OnChanged
            while (true)
            {

            }
    }

And then just a simple:

    public static void OnChanged(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("File has changed");
    }

What would be a better way in a windows service to do this?


Solution

  • You can start a message pump using Application.Run() from WinForms.

    using System.Windows.Forms;
    // The class that handles the creation of the application windows
    class MyApplicationContext : ApplicationContext {
    
        private MyApplicationContext() {
            // Handle the ApplicationExit event to know when the application is exiting.
            Application.ApplicationExit += new EventHandler(this.OnApplicationExit);
    
            log_watcher = new FileSystemWatcher();
            log_watcher.Path = Path.GetDirectoryName(pathToFile);
            log_watcher.Filter = recent_file.Name;
            log_watcher.NotifyFilter = NotifyFilters.LastWrite;
            log_watcher.Changed += new FileSystemEventHandler(OnChanged);
    
            log_watcher.EnableRaisingEvents = true;
        }
    
        public static void OnChanged(object sender, FileSystemEventArgs e) {
            Console.WriteLine("File has changed");
        }
    
        private void OnApplicationExit(object sender, EventArgs e) {
            Console.WriteLine("File monitor exited.");
        }
    
        [STAThread]
        static void Main(string[] args) {
    
            // Create the MyApplicationContext, that derives from     ApplicationContext,
            // that manages when the application should exit.
    
            MyApplicationContext context = new MyApplicationContext();
    
            // Run the application with the specific context. It will exit when
            // all forms are closed.
            Application.Run(context);
    
        }
    }
    

    See Run(ApplicationContext) on learn.microsoft.com.