FileSystemWatcher (WaitForChanged)

M

Megan

I have a windows service that monitors a folder. I have a
routine to process XML files whenever a new file gets
created (in the folder that the Filesystemwatcher is
monitoring.)
Since the files are large, before the copy process is
completed the Created event fires first, and I get errors
because I'm trying to read the xml file on to a stream
for further process.
The Created event gets raised when I copy and paste a new
xml file onto folder (but fires before the file is fully
copied). I need some help on how to use the
WaitForChanged method in this example.

Thanks
-Megan

sample code:
A Windows service loads this class and on it's
MyService.OnStart() sets the FSW's EnableRaisingEvents.
(resets on MyService.OnStop())

Class FSMonitor
private MyWatcher as FileSystemWatcher
Public Sub New()
MyWatcher = New FileSystemWatcher
With MyWatcher
.Path = "c:\MyFolder"
.Filter = ".xml"
.IncludeSubDirectories = False
.NotifyFilter = NotifyFilters.CreationTime Or
NotifyFilters.LastWrite OR etc..

AddHandler .Created AddressOf OnChanged()
End With

Private Sub OnChanged(byval obj as object, byval e as
FileSystemEventArgs)
If e.ChangeType = WatcherChangeTypes.Created Then
'process large xml file
Try

Dim MyReader as New StreamReader(e.FullPath)
ProcessXMLFile(MyReader)

Catch ex as Exception
Debug.Writeline(ex.message)
Finally
End Try
End If
End Sub
End Class
 
A

Alireza Kheyrollahi

Hi Megan,

I am not sure you are still looking for answer but:

If you are not already using NTFS, you might benefit from its being
transactional. It means unless a file is completely copied, it practically
does not exist on the system. I am not sure about VFAT.

If it is already NTFS, you might use an approach like this:

Do Until PathFileExists(copiedFile)
Thread.Sleep(2000)
Loop

Cheers
Ali
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top