文件观察程序事件触发

本文关键字:事件 程序 观察 文件 | 更新日期: 2023-09-27 18:37:19

我有一个方法如下

 public void Run()
        {
            // Create a new FileSystemWatcher and set its properties.
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = "C:''model_RCCMREC";
            /* Watch for changes in LastAccess and LastWrite times, and
               the renaming of files or directories. */
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            //   watch wav files.
            watcher.Filter = "*.wav";
            // Add event handlers. 
            watcher.Created += new FileSystemEventHandler(OnChanged);
            // Begin watching.
            watcher.EnableRaisingEvents = true;
        }

和 Onchanged 事件处理程序作为

public  void OnChanged(object source, FileSystemEventArgs e)
        {
//I AM DOING SOMETHNG HERE
}

实际上,我想在每次将新文件添加到文件夹时运行Onchanged事件处理程序。为了模拟新文件的添加,我做了一个测试方法

  public void test()
        { 
                File.Move(@"C:/TAKE_FORM_HERE_RCCM/59947874_59858856_03022013_074051_785_787_490_108.wav", @"C:/model_RCCMREC/59947874_59858856_03022013_074051_785_787_490_108.wav");
                 Run();
        }

但是,当我运行程序时,永远不会到达 OnChanged 事件处理程序。

为什么会这样?或者我做错了什么?

文件观察程序事件触发

您的问题是您在初始化并启动文件系统观察器之前移动文件。要修复此调用,请先运行()。

public void test()
    { 
      Run();                 
      File.Move(@"C:/TAKE_FORM_HERE_RCCM/59947874_59858856_03022013_074051_785_787_490_108.wav", @"C:/model_RCCMREC/59947874_59858856_03022013_074051_785_787_490_108.wav");
    }

试试这个

instead of using "created" Event use "Deleted" Event
watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);

OnChange will occur if any change occurs in that particular folder , 
First set a path and put a text file inside it and run your exe or web app 
then rename any file inside the folder so that your event will come