FileSystemWatcher异常上升

时间:2012-08-30 10:07:53

标签: c# filesystemwatcher

我写了一个小应用程序来监控文件的变化。 当我运行它时,每次我对Path都有例外。我无法理解为什么。路径确实存在。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Run();
        }

        public static void Run()
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = @"D:\test\1.txt";
            watcher.NotifyFilter = NotifyFilters.LastWrite;

            watcher.Changed +=new FileSystemEventHandler(watcher_Changed);
            watcher.EnableRaisingEvents = true;
        }

static void  watcher_Changed(object sender, FileSystemEventArgs e)
{
    Console.WriteLine(e.ChangeType);
}


    }
}

1 个答案:

答案 0 :(得分:1)

FileSystemWatcher.Path应该是Path而不是文件名

watcher.Path = @"D:\test"; 
watcher.Filter = "1.txt";

private static void watcher_Changed(object source, FileSystemEventArgs e)
{
    // this test is unnecessary if you plan to monitor only this file and
    // have used the proper constructor or the filter property
    if(e.Name == "1.txt")
    {
         WatcherChangeTypes wct = e.ChangeType;
         Console.WriteLine("File {0} {1}", e.FullPath, wct.ToString());
    }
}

您还可以使用带有两个参数的构造函数来限制监视,即路径和文件过滤器。

FileSystemWatcher watcher = new FileSystemWatcher(@"d:\test", "1.txt");  

See MSDN References