FileSystemWatcher“包装器”未触发事件

时间:2019-12-12 22:12:40

标签: c# filesystemwatcher

我为FileSystemWatcher创建了一个包装器类,但是无法触发事件。使用FileSystemWatcher类时,它们会按预期方式触发,而不是我的包装器。

有什么想法吗?

public class FolderWatcher
{
    public event FileSystemEventHandler Created;
    public event FileSystemEventHandler Changed;
    private FileSystemWatcher _watcher;

    public FolderWatcher(string watchedFolderPath)
    {
        _watcher = new FileSystemWatcher(watchedFolderPath);
        _watcher.Created += Created;
        _watcher.Changed += Changed;
        _watcher.EnableRaisingEvents = true;
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        string watchedFolder = "/home/user";

        // 1. Custom wrapper for FileSystemWatcher. No events get fired.
        FolderWatcher watcher = new FolderWatcher(watchedFolder);

        // 2. The built in FileSystemWatcher works as expected. Uncomment to test.
        // FileSystemWatcher watcher = new FileSystemWatcher(watchedFolder);
        // watcher.EnableRaisingEvents = true;

        bool createdTriggered = false;
        bool changedTriggered = false;
        bool wait = (changedTriggered == false && createdTriggered == false);

        watcher.Created += (sender, args) => 
        {
            createdTriggered = true;
            Console.WriteLine($"{args.Name} created!");
        };

        watcher.Changed += (sender, args) => 
        {
            changedTriggered = true;
            Console.WriteLine($"{args.Name} changed!");
        };

        Console.WriteLine($"Watching folder {watchedFolder}");

        while (wait)
        {
            await Task.Delay(1);
        }

        Console.WriteLine("Closing application...");
    }
}

为了测试这一点,我刚刚启动了它并创建了一个新文件/编辑了/home/user中的现有文件。方案1(在代码中注释)不会触发事件,但是方案2(在代码中注释)不会触发事件。我正在努力找出原因。

值得一提的是,我对this answer.的关注度很低

2 个答案:

答案 0 :(得分:2)

与其尝试将File Watcher的事件挂接到您的事件,不如在捕获File Watcher的事件时触发事件。

<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.2.0/css/all.css" />
<input type="file" id="inputName" class="visually-hidden"/>
<label for="inputName">upload</label>

您的活动在那里,有人正在使用您的班级进行挂接。

答案 1 :(得分:0)

要简化Robert Harvey的答案,只需将构造函数更新为:

    public FolderWatcher(string watchedFolderPath)
    {
        _watcher = new FileSystemWatcher(watchedFolderPath);

        _watcher.Created += (sender, args) =>
        {
            if (this.Created != null)
            {
                this.Created(sender, args);
            }
        };

        _watcher.Changed += (sender, args) =>
        {
            if (this.Changed != null)
            {
                this.Changed(sender, args);
            }
        };

        _watcher.EnableRaisingEvents = true;
    }