文件监视器事件触发

时间:2013-10-29 07:07:17

标签: c# filesystemwatcher

我有一个方法如下

 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事件处理程序。

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

2 个答案:

答案 0 :(得分:3)

您的问题是您正在移动文件,然后初始化并启动 FileSystemWatcher 。要先修复此操作 Run()

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

答案 1 :(得分:0)

试试这个

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