在FileSystemWatcher监视目录时等待

时间:2017-10-25 20:24:02

标签: c# logging windows-services filesystemwatcher

我正在尝试监视日志文件以进行更改。我的代码正在运行,并尽其所能。但是,因为我希望它作为Windows服务运行并且不断监视我不确定将其设置为等待状态的正确方法。这是它目前正在做的事情。

    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)
            {

            }
    }

然后只是一个简单的:

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

在Windows服务中执行此操作会有什么更好的方法?

1 个答案:

答案 0 :(得分:0)

您可以使用WinForms中的Application.Run()启动消息泵。

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);

    }
}

请参阅docs.microsoft.com上的Run(ApplicationContext)