简体   繁体   English

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

[英]Access Method from FileSystemWatcher Event Handler in C#

I am trying to access a method from inside an event handler using the FileSystemWatcher. 我试图使用FileSystemWatcher从事件处理程序内部访问方法。 It seems like variations of this question have been asked but I sure can't seem to use any of them to answer to this point. 似乎已经问过这个问题的变化,但我肯定似乎无法使用它们中的任何一个来回答这一点。 In the code below I want to be able to access ReadNoteFile from OnChanged but cannot. 在下面的代码中,我希望能够从OnChanged访问ReadNoteFile但不能。 Any help would be greatly appreciated. 任何帮助将不胜感激。

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
    }

The FileSystemEventHandler constructor expects (object, IntPtr) arguments. FileSystemEventHandler构造函数需要(object, IntPtr)参数。

I suggest skipping the creation of another object and pass a lambda directly (as is usual practice nowadays in this scenario): 我建议跳过另一个对象的创建并直接传递一个lambda(如今在这种情况下的惯常做法):

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

FileSystemWatcher#Changed FileSystemWatcher的更改#

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM