This is an extract of an article I wrote lately
(
http://www.utmag.com/wconnect/wc.dll?LevelExtreme~9,7,10,,792) :
After a week that my application was running correctly, it suddenly stopped
without any errors. My application was still running but stopped receiving
events when files where created. After digging, I discovered that the
network connection has cut for about 2 minutes the night before. Since the
cut, no events were raised. This behavior can easily be tested simply by
deleting the root folder you set in the Path property. I had to find a
solution! Here is one I will share with you. You need to do two
modifications to the code above. The first one concerns the Error event
handler. Change the code you have for this event for this new one:
Private Sub FSWError( _
ByVal sender As Object, _
ByVal e As System.IO.ErrorEventArgs)
'Signature to use for the Error event
lstEvents.Items.Add("FSWError detected some activity at " & _
Date.Now.ToString)
lstEvents.Items.Add(" " & e.GetException.ToString)
FileSystemWatcher1.EnableRaisingEvents = False
Do Until FileSystemWatcher1.EnableRaisingEvents
Application.DoEvents()
Try
InitFSW()
FileSystemWatcher1.EnableRaisingEvents = True
lstEvents.Items.Add(" Now back to work!!! " & _
Date.Now.ToString)
Catch ex As Exception
FileSystemWatcher1.EnableRaisingEvents = False
lstEvents.Items.Add(" Still have problems with the folder at "
& _
Date.Now.ToString)
Threading.Thread.Sleep(5000)
End Try
Loop
End Sub
When the folder is deleted (or when the network connection gets cut), an
error is raised and the FileSystemWatcher object gets corrupted. This code
simply tries to reset the FileSystemWatcher properties and to re-enable it.
If this succeeds, it means that everything is back to normal.
I have said 2 modifications. This second modification is that you need to
remove the handler to the events when you recreate the FileSystemWatcher
object. You need to add these lines to the InitFSW method before setting the
Path property:
'Remove handlers of the previous instance
RemoveHandler .Changed, AddressOf FSWHandler1
RemoveHandler .Created, AddressOf FSWHandler1
RemoveHandler .Deleted, AddressOf FSWHandler1
RemoveHandler .Renamed, AddressOf FSWHandlerRename
RemoveHandler .Error, AddressOf FSWError
If you don't remove the handlers and your FileSystemWatcher has errors and
is recreated, you will receive one event for every time the AddHandler has
been executed.
--
HTH
Éric Moreau, MCSD, Visual Developer - Visual Basic MVP
(
http://aspnet2.com/mvp.ashx?EricMoreau)
Conseiller Principal / Senior Consultant
Concept S2i inc. (
www.s2i.com)