2017-10-25 16 views
-1

変更のログファイルを監視しようとしています。私のコードは動作しており、必要なものはすべて実行します。しかし、これをWindowsサービスとして実行し、常に監視したいので、私はそれを待機状態にする適切な方法が不明です。これは現時点で何をしているのですか?FileSystemWatcherがディレクトリを監視している間待機中

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

      } 
    } 

そして単純な:これを行うには、Windowsのサービスでより良い方法だろう何

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

+0

これはWindowsサービスコードではなく、コンソールアプリケーションです。まず、 "start"、 "stop"などに応答するメッセージポンプ(winformsコードのような)がある場所で正しいサンプルを作成してください。 –

+0

@LB私のコードはサービスに入れる前にデバッグimo – Tom

+0

しかし、コンソールアプリケーションは、テストする正しい方法ではありません。少なくともwinformsアプリケーションを使用してください –

答えて

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)を参照してください。

関連する問題