从C#中的FileSystemWatcher事件处理程序访问方法

时间:2019-04-16 16:17:34

标签: c#

我正在尝试使用FileSystemWatcher从事件处理程序内部访问方法。似乎有人问过这个问题的变体,但我确定似乎无法使用它们中的任何一个来回答这一点。在下面的代码中,我希望能够从OnChanged访问ReadNoteFile,但不能。任何帮助将不胜感激。

public void CreateFileWatcher(string path)
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = path;

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

        watcher.Filter = "*.txt";

        watcher.Changed += new FileSystemEventHandler(OnChanged);

        watcher.EnableRaisingEvents = true;
    }


public static void OnChanged(object source, FileSystemEventArgs e)
    {
        MessageBox.Show("New note has arrived!");

        //run ReadNoteFile here

    }

public void ReadNoteFile(string path)
    {
        //do some stuff
    }

1 个答案:

答案 0 :(得分:0)

FileSystemEventHandler构造函数需要(object, IntPtr)自变量。

我建议跳过另一个对象的创建并直接传递一个lambda(在这种情况下,这是当今的惯例):

watcher.Changed += delegate() { MessageBox.Show("New note has arrived!"); };

FileSystemWatcher#Changed