Dynamically create filewatchers based on entries in the app.config file for a windows service

I've created a windows service whose purpose is to move files from the local disk to shared network drives.  I've got the basics working on the dev machine but I'm looking to expand the functionality and have hit a stumbling block.  At the start this service should be able to read the app.config file and for each setting that it finds it should create a new filewatcher.  The value of the setting key will contain the origin folder and the target location.   It will set the new filewatcher properties and then add each watcher to an array.  What I'm struggling with is how to code for the FileSystemWatcher_Created event of each watcher in the array, which is where the actual file moves will take place.  Here's what I have so far.  Can someone help me get to the next steps?


Dim mycount As Integer = System.Configuration.ConfigurationSettings.AppSettings.Count
        Dim x As Integer = 0
        Dim mysetting As String = ""
        Dim myarray(0) As System.IO.FileSystemWatcher

        For x = 0 To mycount - 1
            mysetting = System.Configuration.ConfigurationSettings.AppSettings(x)
           ' the first setting is a TESTPARM that should be skipped
            If mysetting = "Y" Or mysetting = "P" Or mysetting = "T" Or mysetting = "" Or _
             IsNothing(mysetting) Or IsDBNull(mysetting) Then
                ' do nothing
            Else
                Dim mytext() As String = Split(mysetting, ";")
                Dim origin As String = mytext(0)
                Dim target As String = mytext(1)
                Dim mywatcher As New FileSystemWatcher
                mywatcher.Path = origin
                mywatcher.IncludeSubdirectories = False
                mywatcher.NotifyFilter = NotifyFilters.FileName
                mywatcher.WaitForChanged(WatcherChangeTypes.Created)
                mywatcher.EnableRaisingEvents = True
                ReDim Preserve myarray(x)
                myarray(x) = mywatcher
            End If

        Next
LVL 1
bozworthyAsked:
Who is Participating?
 
Wayne Taylor (webtubbs)Connect With a Mentor Commented:
Hi bozworthy,

Use something like this....

                ........
                myarray(x) = mywatcher
                AddHandler mywatcher.Created, AddressOf FileSystemWatcher_Created

...then this sub to handle the created event for each....

    Private Sub FileSystemWatcher_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs)
        Dim mywatcher As FileSystemWatcher = CType(sender, FileSystemWatcher)
        'etc
    End Sub

Regards,

Wayne
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.