There is alot of post out there about this, all revolving around a common solution. I have attempted to use this solution but do not believe it's as reliable as i had hoped. If anyone could point out what i am doing wrong or suggestions to make it more full proof please post!
Situation: Watching shared network folders..if network is lost, filewatcher loses what it was trying to watch and service dies. The following code does work but not all the time. The event gets fired when it attempts to set the path property of the FS. If the path cant be found(network down) it throws an exception. I catch it and basically sleep for x time and try again. Ideally it sounds like it would work fine but it isn't as reliable as it appears :(
Protected Overrides Sub OnStart(ByVal args() As String)
fs1 = New FileSystemWatcher
fs1.Filter = My.Settings.MonitoringFilter
' fs1.NotifyFilter = NotifyFilters.LastWrite
fs1.Path = My.Settings.MonitoringDirNOSlash
' Add event handlers.
AddHandler fs1.Error, AddressOf WatcherError
fs1.EnableRaisingEvents = True
End Sub
Protected Sub WatcherError(source As Object, e As ErrorEventArgs)
fs1.Dispose()
fs1 = New FileSystemWatcher
Dim c As Integer = 0
While Not fs1.EnableRaisingEvents
Try
fs1.Filter = My.Settings.MonitoringFilter
fs1.Path = My.Settings.MonitoringDirNOSlash
AddHandler fs1.Error, AddressOf WatcherError
fs1.EnableRaisingEvents = True
Catch ex As Exception
c += 1
If c = 1 Then
ErrorReport(ex.Message)
End If
System.Threading.Thread.Sleep(5000)
End Try
End While
End Sub