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"

Community
  • 1
  • 1
Jiew Meng
  • 84,767
  • 185
  • 495
  • 805
  • 3
    check out [filewatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) – Matt Ellen Oct 19 '10 at 09:51
  • 1
    Possibly related question which answers more than you're asking for, but will probably help with what you're trying to do: http://stackoverflow.com/questions/239988/filesystemwatcher-vs-polling-to-watch-for-changes – Benjol Oct 19 '10 at 09:51
  • @benjol: your linked question exactly mirrors my experience. – Eamon Nerbonne Oct 19 '10 at 09:59
  • Don't use filewatcher, because you'll enter a realm of pain that you probably don't want to. Poll the file for changes - look at date first, then size, then, the content. – Daniel Mošmondor Oct 19 '10 at 10:49
  • @Daniel Mošmondor, will that be very slow? – Jiew Meng Oct 19 '10 at 12:49
  • @Daniel Mošmondor, I guess it shouldn't be a problem for me :) I am creating something like a text editor. but just curious – Jiew Meng Oct 19 '10 at 13:31
  • Also, I just discovered that `FileSystemWatcher` is not working for me ... see [sister question](http://stackoverflow.com/questions/3967658/c-using-filesystemwatcher-to-watch-for-changes-to-files) for updates – Jiew Meng Oct 19 '10 at 13:32

3 Answers3

9

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

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
5

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
  • 47,023
  • 20
  • 101
  • 166
4

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

Vilx-
  • 104,512
  • 87
  • 279
  • 422
  • 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) – Jiew Meng Oct 19 '10 at 11:04