在C#中检查文件系统观察程序

时间:2015-09-09 14:31:11

标签: c# file-watcher

我已编写此代码用于在系统中查看文件,但它不会警告文件夹或文件中的任何修改。我怎样才能做到这一点?我不理解,因为它没有显示任何例外或错误。

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

2 个答案:

答案 0 :(得分: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");
    }

答案 1 :(得分:2)

FileSystemWatcher.NotifyFilter Property

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