• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

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
                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.EnableRaisingEvents = True
                ReDim Preserve myarray(x)
                myarray(x) = mywatcher
            End If

1 Solution
Wayne Taylor (webtubbs)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)
    End Sub



Featured Post

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now