开发者

FileSystemWatcher is not working

开发者 https://www.devze.com 2023-01-09 11:36 出处:网络
I added FileSystemWatcher in Form1_Load like this: Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

I added FileSystemWatcher in Form1_Load like this:

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

I have an OnChanged function which is a simple MessageBox. Still, when I change the status.txt file, no message box is shown.


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

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

You may notice in certain situations that a single creation event generates multiple Created events that are handled by your component. For example, if you use a FileSystemWatcher component to monitor the creation of new files in a directory, and then test it by using Notepad to create a file, you may see two Created events generated even though only a single file was created. This is because Notepad performs multiple file system actions during the writing process. Notepad writes to the disk in batches that create the content of the file and then the file attributes. Other applications may perform in the same manner. Because FileSystemWatcher monitors the operating system activities, all events that these applications fire will be picked up


You should also listen for the Deleted event.

Depending on the editor you're using, they sometimes Delete/Replace the file instead of simply changing it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号