Reputation: 321
I'm having a problem trying to work out how to watch a folder for changes. This is how far I've got:
Class MainWindow
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Dim Path As String = "C:\Temp"
' Create a new FileSystemWatcher and set its properties.
Dim watcher As New FileSystemWatcher()
watcher.Path = Path
' Watch for changes in LastAccess and LastWrite times, and
' the renaming of files or directories.
watcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName)
' Only watch text files.
watcher.Filter = "*.txt"
' Add event handlers.
AddHandler watcher.Changed, AddressOf OnChanged
AddHandler watcher.Created, AddressOf OnChanged
AddHandler watcher.Deleted, AddressOf OnChanged
AddHandler watcher.Renamed, AddressOf OnRenamed
' Begin watching.
watcher.EnableRaisingEvents = True
End Sub
' Define the event handlers.
Private Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
' Specify what is done when a file is changed, created, or deleted.
MsgBox("File: " & e.FullPath & " " & e.ChangeType)
End Sub
Private Shared Sub OnRenamed(ByVal source As Object, ByVal e As RenamedEventArgs)
' Specify what is done when a file is renamed.
MsgBox("File: {0} renamed to {1}", e.OldFullPath, e.FullPath)
End Sub
End Class
The problem is when a change occurs in the folder the program exits with no error code. I've read a few related posts and I know it has something to do with thread safety. However I've no idea how to make this program "thread safe". Can anyone give me some advice? Thanks!
Upvotes: 0
Views: 2402
Reputation: 4346
I'm not getting any thread safety issues here. I think the problem is:
MsgBox("File: {0} renamed to {1}", e.OldFullPath, e.FullPath)
should be
MsgBox(String.Format("File: {0} renamed to {1}", e.OldFullPath, e.FullPath))
Upvotes: 2