I have an .xml file that I am using as a configuration file that is loaded during application startup. I have created a FileSystemWatcher object and set it to filter the FileName and LastWrite .xml file to filter on Changed and Rename events. When the file is renamed, a message is popped and the application is terminated. If the file is edited and saved I call the subs to reload the .xml file. The rename changetype event operates correctly - it fires only once. However when the file is edited and saved, the Changed event is fired three times. I have coded around the problem but am not confident in whether it will always work as intended - why three times and will it always be three times on all computers? Can't find anything on M$ site about the potential cause of this!
Code extract follows:
Public Module Startup
Private intChanged As Integer = 0
Public Sub Main()
' Create FileSystemWatcher and set properties
Dim watcher As New FileSystemWatcher
watcher.Path = Application.StartupPath
' Watch for changes in LastWrite times and file rename
watcher.NotifyFilter = NotifyFilters.FileName Or NotifyFilters.LastWrite
'Only watch the app config file
watcher.Filter = "Config.xml"
AddHandler watcher.Changed, AddressOf OnChanged
AddHandler watcher.Deleted, AddressOf OnChanged
AddHandler watcher.Renamed, AddressOf OnRenamed
' Begin watching.
watcher.EnableRaisingEvents = True
LoadConfig(Application.StartupPath & "\" & Config.xml)
'.... load the GUI
Private Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
' Execute when file is changed.
intChanged += 1
' Msgbox(Cstr(e.ChangeType) & " event fired " & intChanged & " time(s)") ' For info
If intChanged = 3 Then
intChanged = 0
LoadConfig(e.FullPath) 'Sub to reload the .xml file
Private Sub OnRenamed(ByVal source As Object, ByVal e As RenamedEventArgs)
' Exit the application if the config file is renamed
MsgBox("File: " & e.OldName & " was renamed to " & e.Name & "!" & _
vbCrLf & "This file is a required application file. The " & _
"application will terminate.", MsgBoxStyle.Critical, "File System Error")
Private Sub LoadConfig(strXMLFile as String)
'Xml file loading & parsing stubs