c# - 在 C# 中检查文件系统监视器

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

最佳答案

我更新了代码。如果要查看添加的新文件,则需要扩展 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");
    }

关于c# - 在 C# 中检查文件系统监视器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32482395/

相关文章:

powershell - 取消注册已注册的 filewatcher 事件不起作用

javascript - 在node-hound中绑定(bind)多个事件?

powershell - 永久监控特定文件夹中文件创建的最有效、最可靠的方法

c# - 如何使用 C# 枚举 GridFS 中的文件

c# - 实现接口(interface)的实体的通用配置

css - 文件观察器不会从 PhpStorm 中的 Less 文件生成 CSS

go - Goland 中的默认文件观察器

c# - Visual C#/WinForms 面板

c# - 有没有办法确定 Microsoft XPS Document Writer 在系统上是否可用且功能正常

c# - 尝试在 ASP.NET Core 应用程序中使用 SmtpClient 发送电子邮件时出现错误