0
class Program
{
    FileSystemWatcher _watchFolder;
    string sPath = @"D:\TestMonitor";
    static void Main(string[] args)
    {
        Program p = new Program();
        Thread t = new Thread(new ThreadStart(p.startActivityMonitoring));
        t.Start();
    }


    private void startActivityMonitoring()
    {
        _watchFolder = new FileSystemWatcher();
        _watchFolder.Path = Convert.ToString(sPath);
        _watchFolder.NotifyFilter = System.IO.NotifyFilters.DirectoryName;
        _watchFolder.NotifyFilter =
        _watchFolder.NotifyFilter | System.IO.NotifyFilters.FileName;
        _watchFolder.NotifyFilter =
        _watchFolder.NotifyFilter | System.IO.NotifyFilters.Attributes;
        _watchFolder.Changed += new FileSystemEventHandler(eventRaised);
        _watchFolder.Created += new FileSystemEventHandler(eventRaised);
        _watchFolder.Deleted += new FileSystemEventHandler(eventRaised);
        _watchFolder.Renamed += new System.IO.RenamedEventHandler(eventRaised);
        _watchFolder.EnableRaisingEvents = true;
    }



    private void eventRaised(object sender, System.IO.FileSystemEventArgs e)
    {
        switch (e.ChangeType)
        {
            case WatcherChangeTypes.Changed:
                Console.WriteLine(string.Format("File {0} has been modified\r\n", e.FullPath));

                break;
            case WatcherChangeTypes.Created:
                Console.WriteLine(string.Format("File {0} has been created\r\n", e.FullPath));

                break;
            case WatcherChangeTypes.Deleted:
                Console.WriteLine(string.Format("File {0} has been deleted\r\n", e.FullPath));

                break;
            default: // Another action
                break;
        }
    }

}

Console.WriteLine を使用して変更をログに記録しようとすると、FileSystemWatcher を使用してディレクトリ内の変更をポーリングする単純なプログラムが機能しません。

Console.WriteLine は任意のスレッド内で適切に機能するため、この問題の原因は不明です

4

1 に答える 1

4

あなたのプログラムは、スレッドを開始した直後に終了しています。プログラムを実行し続ける必要があります。簡単な方法の 1 つは、プログラムの終了を停止するために Console.ReadLine を含めることです。

static void Main(string[] args)
    {
        Program p = new Program();
        Thread t = new Thread(new ThreadStart(p.startActivityMonitoring));
        t.Start();
        Console.Writeline("Press enter to exit");
        Console.ReadLine();
    }

ここに画像の説明を入力

于 2013-01-01T05:58:28.580 に答える