Question

I have a method as follows

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

and the Onchanged event handler as

public  void OnChanged(object source, FileSystemEventArgs e)
        {

//I AM DOING SOMETHNG HERE

}

I want actually to run the Onchanged event handler each time when a new file is added to a folder. To simulate the adding of the new file i did a test method

  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();

        }

However,when I run the program the OnChanged event handler is never reached.

Why is it so ? or what am I doing wrong ?

Was it helpful?

Solution

Your problem is that you are moving the file before you initialize and start the FileSystemWatcher. To fix this call Run() first.

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

OTHER TIPS

try this

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top