1

我已经编写了这段代码来查看系统中的文件,但它不会提醒文件夹或文件中的任何修改。我怎样才能做到这一点?我不明白,因为它没有显示任何异常或错误。

static void Main(string[] args)
{
  FileSystemWatcher();
}

public static void FileSystemWatcher()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = @"D:\watcher";
    watcher.NotifyFilter = NotifyFilters.LastWrite;
    watcher.Filter = "*.*";
    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.EnableRaisingEvents = true;
    Console.Read();
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
   Console.WriteLine(e.Name + " has changed");
}
4

2 回答 2

3

我更新了代码。如果要查看添加的新文件,需要扩展 NotifyFilter

    static void Main(string[] args)
    {
        FileSystemWatcher();
    }

    public static void FileSystemWatcher()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"D:\temp";
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "*.*";
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += Watcher_Created;
        watcher.Renamed += Watcher_Renamed;
        watcher.EnableRaisingEvents = true;
        Console.Read();
    }

    private static void Watcher_Renamed(object sender, RenamedEventArgs e)
    {
        Console.WriteLine(e.Name + " has been renamed");
    }

    private static void Watcher_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine(e.Name + " has been added");
    }

    private static void OnChanged(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine(e.Name + " has changed");
    }
于 2015-09-09T14:41:07.677 回答
2

FileSystemWatcher.NotifyFilter 属性

watcher.NotifyFilter <- is flag enum!

你需要写:

watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
       | NotifyFilters.FileName | NotifyFilters.DirectoryName;

...
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
于 2015-09-09T14:43:42.863 回答