If you need to monitor for a file change then use the FileSystemWatcher type. Create an instance of the type and give it the name of the file (or folder) to watch. Then handle the event(s) that you care about. In general for a file modification it can be triggered either by updating an existing file or by creating a new file (after deleting the original file). It completely depends on how the file is modified on the other side. So handle the Changed
and Created
events. When these events are raised then the file has been modified and you should reload the data.
Refer to the docs linked above for a full example. Pay careful attention to the fact that you need to set EnableRaiseEvents
to actually start getting events. Don't do this until you're ready to start listening.
Caveat to using FSW, it runs while the IO operation is in process. Therefore your event handler may get called while the file is still open by the other process. Additionally a single write by a process can trigger multiple Changed
events so don't assume that the file is fully written when the event is raised. Yet another concern is that this runs as part of the underlying journaling API and therefore needs to be very fast so it doesn't slow down IO. The general recommendation is to set an indicator or queue a work item and return immediately from the handler. Have a background thread or timer periodically check the indicator/queue for work and process it later on. Given that the file may still be locked when you process the file you need to handle this case and retry later. Also remember that the file may be partially written so if you're using XML then XML parsing may fail. You should retry later. There are any # of ways to implement a queue/retry process so you can search for options there but a simple ReaderWriterLock instance is generally sufficient. Just be careful about race conditions as one thread is adding data while another is removing it.