C# FileSystemWatcher Event

442 views Asked by At

I have to follow changes of one of folder.

class FileWatcher
{
    FileSystemWatcher watcher = new FileSystemWatcher();

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public void StartWatching()
    {
        watcher.Path = AppDomain.CurrentDomain.BaseDirectory + "\\Read test data";

        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;            

        watcher.Changed += new FileSystemEventHandler(OnChanged);

        watcher.EnableRaisingEvents = true;
     }

    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        Console.WriteLine("Changes in folder: 'Read test data' ");           
    }
}

And initialization:

private FileWatcher watch = new FileWatcher();

    private void StartReadCVSChanges_Click(object sender, EventArgs e)
    {    
        watch.StartWatching();
    }  

For some reason when I do have some changes the event handler is called 3 times:

enter image description here

I prefer it to be once.

Any ideas?

1

There are 1 answers

0
sm.abdullah On

see this link Text from there.

You may notice in certain situations that a single creation event generates multiple Created events that are handled by your component. For example,if you use a FileSystemWatcher component to monitor the creation of new files in a directory,and then test it by using Notepad to create a file, you may see two Created events generated even though only a single file was created. This is because Notepad performs multiple file system actions during the writing process. Notepad writes to the disk in batches that create the content of the file and then the file attributes. Other applications may perform in the same manner.Because FileSystemWatcher monitors the operating system activities, all events that these applications fire will be picked up