Click here to Skip to main content
15,878,970 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am writing to excel file. I am raising a event whenever the excel file changes.

C#
private void FileChanged()
       {

           watcher.Path = DirectoryPath;
           watcher.Filter = "*.xlsx";
           watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;

           watcher.Changed += new FileSystemEventHandler(OnChanged);
           watcher.EnableRaisingEvents = true;

       }



I am expecting the OnChanged method would be called when I Open the file for writing but I am seeing the OnChanged method keeps getting called several times.

In the OnChanged method I am not doing anything if it is the same process. Only if it is a different process then I am reading from excel file.

Your help is appreciated.
Posted

MSDN[^] wrote:
Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.

What you will likely need to do is buffer the events coming out of the FileSystemWatcher.

Something like the following might work[^].

You might want to do some digging around for other implementations, as I'm not familiar with that but it seems like that could prove useful as a starting point.

Enjoy.
 
Share this answer
 
JSOP also has two articles which (may) help you understand some of the things going on - see

FileSystemWatcher - Pure Chaos (Part 1 of 2)[^]

and part 2, particularly for the 'quirks'

FileSystemWatcher - Pure Chaos (Part 2 of 2)[^]


'G'
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900