0

我有一个方法如下

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

为什么会这样?还是我做错了什么?

4

2 回答 2

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");
    }
于 2013-10-29T07:19:35.637 回答
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
于 2013-10-29T07:15:09.993 回答