views:

2754

answers:

3

Is there any way to determine if a text file is currently open in a text editor? Or better yet, is there a way to trigger an event when a text file is opened (from any program)?

+4  A: 

Using the FileSystemWatcher component you can detect Changed, Created, Deleted, and Renamed events statically.

If you want to detect Last Access you need to manually set the NotifyFilter to include LastAccess.

Tom Anderson
Any idea what the NotifyFilter of LastAccess does in relation to FileSystemWatcher? How would I use that?
John
updated for you.
Tom Anderson
If I set the NotifyFilter, I don't think it will invoke an event unless a Changed, Created, Deleted, or Renamed event occurs. I guess LastAccess doesn't offer what I need.
John
A: 

I think I'll make a Timer that checks the last modified time of the file.... and when the program starts, it'll get the last modified time.

John
I am not sure why you'd want a timer in this situation, you haven't mentioned any re-occuring process. If you are interested in determining if the file has been saved during the time your program is running, I'd follow Tom's advise and go with the FileSystemWatcher
Nathan Koop
I want to know if a file has been opened (not necessarily saved) during the runtime of my program. Thus, I can check every, say, 100 ms to see if the last modified timestamp has changed. If it is, it is safe to say that the file has been opened within 100 ms time.
John
The modified timestamp will not tell if you a file has been opened - only if it was saved.
Jon B
Hmm. That's not good.
John
Couldn't I use: File.GetLastAccessTime()
John
+1  A: 

When most editors have a file open they typically follow a set strategy:
1. Open File
2.Read entire contents into buffer
3.Close File

Then your program runs. Since the file is already closed, any attempts to open it will of course succeed. Using a FileSystemWatcher this can be detected if a file is open or closed. However, you will not be able to detect if the file has been open prior to your program running.

hova
How would I detect if a file is opened while my program is running?
John
(My program will be running before they even open the file)
John