2009-04-29 35 views
1

我工作的一个Windows服务,手表的几个文件夹的变化,有所创造,有所缺失。除了一个监视单个文件(带有配置设置的XML文件)的细微变化的监视器之外,它一切正常。FileSystemWatcher的更改事件没有被提出

我试着服用Windows服务代码,并把它变成一个简单的Windows应用程序与启动/停止文件系统观察家按钮,并通过它加强。它从不检测XML配置文件的文件更改。这些更改确实发生,文件的“修改日期”正在更新。

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 

这是一些代码,这是XML文件的样本:

<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> 

回答

11

我相信问题是NotifyFilter值。您实际上只告诉FileSystemWatcher查找文件名称更改。为了让它也提高Changed事件以进行文件修改,您还需要指定LastWrite标志。

即代码此时,相应的行应改为:

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

更多信息,请参阅MSDN上的NotifyFilters页面。

注意:正如Joshua Belden指出的那样,甚至根本不需要设置NotifyFilter属性,因为MSDN指出:“默认值是LastWrite,FileName和DirectoryName的按位或组合。但是,我认为这是最好要明确在这种情况下 - 它,然后使它十分明显,以什么FileSystemWatcher是,是不是

+0

谢谢!我欣赏的帮助 – Paxenos 2009-04-29 15:43:04

1

您需要将您的.NotifyFilter更改为类似LastWrite拿起变化,我相信。

MSDN链接here

0

此代码似乎对我的工作,拿起编辑到的test.xml文件。是

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 

转储通知过滤器一起。

+0

从MSDN(http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.notifyfilter.aspx):“默认为LastWrite,文件名,目录名和的按位或组合“。所以是的,你不需要指定NotifyFilter的那一行,但是明确你所关注的内容并不会伤害你。 (无论如何,我会把它包括在内)。) – Noldorin 2009-04-29 15:39:14