代码之家  ›  专栏  ›  技术社区  ›  Shubham

FileSystemWatcher不工作

  •  2
  • Shubham  · 技术社区  · 16 年前

    我补充说 FileSystemWatcher 在Form1中,这样加载:

    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
    

    我有一个onchanged函数,它是一个简单的消息框。不过,当我改变 status.txt 文件,不显示消息框。

    2 回复  |  直到 16 年前
        1
  •  5
  •   Kefala    16 年前
    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
    

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

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

        2
  •  0
  •   Justin Niessner    16 年前

    您还应该监听删除的事件。

    根据您使用的编辑器的不同,它们有时会删除/替换文件,而不是简单地更改文件。