Question

We use a FileSystemWatcher to monitor documents opened from our Document Management system, and if the user saves the document, we ask if they would also like them updated in our system.

We have a problem with XLS files in Excel 2007 (have not verified that the problem does not exist in 2003, but it only seems to be files that open in compatibility mode in 2007) where the Changed event fires immediately upon opening the file, and then once more upon closing the file, even if nothing has changed or the user chooses not to save upon closing. This same behavior does not exist when opening XLSX files.

I wrote a test app to verify the behavior, which you can find at (http://www.just2guys.net/SOFiles/FSWExcel.zip). In the app, there is one FileSystemWatcher for each NotifyFilter type, so that it is apparent why the Changed event was fired.

Any way you can think of to only prompt the user when the document is actually saved in some way by the user? I can start monitoring the file after Process.Start is called, which allows me to skip the message upon opening the document, but I still get one upon closing the document, even when nothing was changed.

Was it helpful?

Solution

I noticed this with Word, and you can simply reproduce it:

If you open a .doc or an .xls file with an Office application, the timestamp changes to the time the document was opened.

If you close the application, the timestamp is reset to its original value (only if you did ont save).

So for Office files, you need two additional checks:

  • on Open, when timestamp is set to current time, check that the file can be opened exclusively

  • on Close, check whether the timestamp is "close to" the current date and time, or check the file's Archive flag

OTHER TIPS

File system watcher is usually evil. It burns a lot of people because it registers events before the file is completely written.

We have been able to get around it by either removing it in lieu of a sleep loop pattern, adding a static delay (Thread.Sleep) before taking action, or a combo of the two (receiving the event, spawning a thread, and looping in the thread until you think that nothing is updating it by checking the last mod date/time).

Excel creates a temporary file each time it opens a file - this is probably the event you are seeing. Check the Name property of FileSystemEventArgs and ignore the event if the filename starts with '~'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top