Click here to Skip to main content
12,947,902 members (81,318 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I am writing to excel file. I am raising a event whenever the excel file changes.

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 4-Jan-13 10:14am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.

Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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)[^]


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

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 5,344
CHill60 3,275
Maciej Los 2,628
Jochen Arndt 1,935
ppolymorphe 1,795

Advertise | Privacy | Mobile
Web02 | 2.8.170518.1 | Last Updated 4 Jan 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100