views:

110

answers:

3

You know the feature for example, you opened C:\test.txt if you also have the same file in another editor, and you edit it there, when you return, the app will prompt that the file has changed, whether you want to update it. How do I check if the file has been updated?

UPDATE

Asked a sister question "Using FileSystemWatcher to watch for changes to files"

+4  A: 

Either use FileSystemWatcher (preferred) or compare the last modified date periodically.

Vilx-
Asked a sister question [Using `FileSystemWatcher` to watch for changes to files](http://stackoverflow.com/questions/3967658/c-using-filesystemwatcher-to-watch-for-changes-to-files)
jiewmeng
+6  A: 

You could use a FileSystemWatcher to get notifications from the file system.

Darin Dimitrov
Asked a sister question [Using `FileSystemWatcher` to watch for changes to files](http://stackoverflow.com/questions/3967658/c-using-filesystemwatcher-to-watch-for-changes-to-files)
jiewmeng
+3  A: 

You can either use a FileSystemWatcher, or you can poll for changes at opportune moments.

Note that the FileSystemWatcher may miss changes if under heavy load and is IDisposable. Failure to dispose it properly can cause stability issues (which I've had happen, personally). If you opt for polling, note that FileInfo caches some metadata so you'll need to call the FileInfo.Refresh method if you reuse FileInfo objects. Alternatively, use the File API.

For only a few files, polling is easier and safer to get right since it avoids the OS callback issues of FileSystemWatcher and never misses any events. For large number of files, the FileSystemWatcher is a must to achieve reasonable performance.

Eamon Nerbonne
No, you don't have to recreate the FileInfo, just call .Refresh() to force it to re-read
Onkelborg
thanks - nice to know! Edited to include that option.
Eamon Nerbonne