2016-07-28 205 views
0

作爲vb中的新手,我在我的FileSystemWatcher中遇到了一些麻煩。由於一些不祥的原因,它不會觸發任何事件。我想檢查目錄中正在複製,刪除或編輯的文件。FileSystemWatcher沒有觸發事件

我很感激任何幫助!

這裏是我的代碼:

Public Class FileWatcher 

Public Sub run(path As String) 
    Dim watcher As New FileSystemWatcher() 

    watcher.Path = path 
    watcher.Filter = "*.xml" 
    watcher.NotifyFilter = NotifyFilters.FileName Or NotifyFilters.LastWrite Or NotifyFilters.CreationTime 

    AddHandler watcher.Changed, AddressOf OnChanged 
    AddHandler watcher.Created, AddressOf OnChanged 
    AddHandler watcher.Deleted, AddressOf OnChanged 
    AddHandler watcher.Renamed, AddressOf OnRenamed 

    watcher.EnableRaisingEvents = True 

End Sub 


Public Function OnChanged(source As Object, e As FileSystemEventArgs) As String 
    ' Returns file name for later use 
    Console.WriteLine("Monitoring: " + e.FullPath) 
    Return e.FullPath 
End Function 

Public Function OnRenamed(source As Object, e As RenamedEventArgs) As String 
    Console.WriteLine("Monitoring: " + e.FullPath) 
    Return e.FullPath 
End Function 

末級

+0

相關:http://stackoverflow.com/a/37553538/3740093 –

回答

0

這裏要考慮的是,觀察者是run方法中的局部變量的第一件事。這意味着您的監視器將在退出運行方法後立即進行垃圾回收。您需要在globlal類級別聲明它,並在該類的實例保持活動狀態,直到完成使用監視代碼。

Public Class FileWatcher 
    Dim watcher As New FileSystemWatcher() 

    Public Sub run(path As String) 

     .... 

接下來請記住,OnChanged和OnRenamed是事件處理程序,因此它們應該聲明爲Sub而不是Function。當然他們不返回任何東西

如果你需要這些處理程序的值,你需要實現某種全局變量來保存你的數據以供進一步處理。一個例子可以是一個列表(字符串列表應擴大添加和刪除文件之間進行區分或更好地使用自己的類和這個類的實例列表)

Dim changedFiles = new List(Of String)() 
Dim renamedFiles = new List(Of String)() 
Public Sub OnChanged(source As Object, e As FileSystemEventArgs) 
    Console.WriteLine("Monitoring: " + e.FullPath) 
    changedFiles.Add(e.FullPath) 
End Sub 

Public Sub OnRenamed(source As Object, e As RenamedEventArgs) 
    Console.WriteLine("Monitoring: " + e.FullPath) 
    renamedFiles.Add(e.FullPath) 
End Sub 
+0

非常感謝! – Lilly

+0

很高興能有所幫助,但只是一個問題。爲什麼你停下來接受可以幫助你的答案? – Steve

+1

對不起,我忘記了 – Lilly