FileSystemWatcher无法正常工作

Shu*_*ham 2 vb.net filesystemwatcher

FileSystemWatcher在Form1_Load中添加了这样的:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ....................
        Dim watcher As New FileSystemWatcher()
        'For watching current directory
        watcher.Path = "/"
        'For watching status.txt for any changes
        watcher.Filter = "status.txt"
        watcher.NotifyFilter = NotifyFilters.LastWrite
        watcher.EnableRaisingEvents = True
        AddHandler watcher.Changed, AddressOf OnChanged
End Sub
Run Code Online (Sandbox Code Playgroud)

我有一个OnChanged函数,它是一个简单的MessageBox.但是,当我更改status.txt文件时,不会显示任何消息框.

Kef*_*ala 5

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim watcher As New IO.FileSystemWatcher()

'For watching current directory
watcher.Path = **System.IO.Directory.GetCurrentDirectory()** 'Note how to obtain current directory
watcher.NotifyFilter = NotifyFilters.LastWrite

'When I pasted your code and created my own status.txt file using 
'right click->new->Text File on Windows 7 it appended a '.txt' automatically so the
'filter wasn't finding it as the file name was status.txt.txt renaming the file
'solved the problem
watcher.Filter = "status.txt" 

AddHandler watcher.Changed, AddressOf OnChanged

watcher.EnableRaisingEvents = True
End Sub

Private Shared Sub OnChanged(ByVal source As Object, ByVal e As IO.FileSystemEventArgs)
MessageBox.Show("Got it")
End Sub
Run Code Online (Sandbox Code Playgroud)

来自http://bartdesmet.net/blogs/bart/archive/2004/10/21/447.aspx

在某些情况下,您可能会注意到单个创建事件会生成由组件处理的多个Created事件.例如,如果使用FileSystemWatcher组件来监视目录中新文件的创建,然后使用记事本创建文件进行测试,即使只创建了一个文件,也可能会看到生成两个Created事件.这是因为Notepad在写入过程中执行多个文件系统操作.记事本批量写入磁盘,创建文件的内容,然后创建文件属性.其他应用程序可以以相同的方式执行.由于FileSystemWatcher监视操作系统活动,因此将拾取这些应用程序触发的所有事件