Question

I'm working on a Windows Service that watches a few folders for changes, creations, and deletions. It all works well with the exception of one watcher that watches a single file (XML File with Configuration Settings) for minor changes.

I tried taking the Windows Service code and putting it into a simple windows application with start/stop buttons for the filesystem watchers and stepped through it. It never detects the file change of the XML config file. The changes are indeed occurring and the "Date Modified" of the file is updating.

XmlEventReferences = New System.IO.FileSystemWatcher()
XmlEventReferences.Path = "C:\XmlReferences\"
XmlEventReferences.Filter = "*.xml"
XmlEventReferences.NotifyFilter = IO.NotifyFilters.FileName
AddHandler XmlEventReferences.Changed, AddressOf ReloadEventReferences
AddHandler XmlEventReferences.Created, AddressOf ReloadEventReferences
AddHandler XmlEventReferences., AddressOf ReloadEventReferences
XmlEventReferences.EnableRaisingEvents = True

That was some of the code and this is a sample of the XML File:

<EventReference>
    <ER_EL_NUMBER>1</ER_EL_NUMBER>
    <ER_SEND_TO_DATABASE>true</ER_SEND_TO_DATABASE>
    <ER_ACTIVATE_ALARM>true</ER_ACTIVATE_ALARM>
    <ER_DESCRIPTION />
</EventReference>
Was it helpful?

Solution

I believe the problem is the value of NotifyFilter. You've actually only told the FileSystemWatcher to look for file name changes. To get it to raise the Changed event for file modifications too, you'll want to specify the LastWrite flag as well.

i.e. The appropiate line of code should be changed to:

XmlEventReferences.NotifyFilter = IO.NotifyFilters.FileName |
    IO.NotifyFilters.LastWrite;

See the NotifyFilters page on MSDN for more info.

Note: As Joshua Belden points out, you don't even need to set the NotifyFilter property at all because as MSDN states: "The default is the bitwise OR combination of LastWrite, FileName, and DirectoryName." However, I would argue that it's always best to be explicit in such cases - it then makes it perfectly obvious as to what the FileSystemWatcher is and is not watching.

OTHER TIPS

You need to change your .NotifyFilter to something like LastWrite to pick up changes i believe.

MSDN link here

This code seemed to work for me, picked up an edit to a test.xml file. Are

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim XmlEventReferences = New System.IO.FileSystemWatcher()
    XmlEventReferences.Path = "C:\"
    XmlEventReferences.Filter = "*.xml"
    XmlEventReferences.EnableRaisingEvents = True
    AddHandler XmlEventReferences.Changed, AddressOf Watch
End Sub

Private Sub Watch(ByVal sender As Object, ByVal e As FileSystemEventArgs)
    Dim s As String = e.FullPath
End Sub

Dump the notify filter all together.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top