vb.net how to start a folder monitor service at runtime and pass on the folder path to monitor?

Posted by mazrabul on Stack Overflow See other posts from Stack Overflow or by mazrabul
Published on 2010-05-27T21:44:34Z Indexed on 2010/05/27 23:01 UTC
Read the original article Hit count: 205

Filed under:
|

hi,

I have the following windows service file:

Imports System.ServiceProcess
Imports System.IO


Public Class fswService
Dim fsw As FileSystemWatcher
Dim lf As StreamWriter

Protected Overrides Sub OnStart(ByVal args As String())
    ' Add code here to start your service. This method should set things
    ' in motion so your service can do its work.
    lf = New StreamWriter(Application.StartupPath & "\fsw_lg.log")
    fsw = New FileSystemWatcher()

    fsw.Path = args(0)
    fsw.IncludeSubdirectories = True
    fsw.Filter = ".txt"
    fsw.EnableRaisingEvents = True

    AddHandler fsw.Created, New FileSystemEventHandler(AddressOf file_created)
    AddHandler fsw.Changed, New FileSystemEventHandler(AddressOf file_changed)
    AddHandler fsw.Deleted, New FileSystemEventHandler(AddressOf file_deleted)
End Sub

Public Sub file_created(ByVal obj As Object, ByVal e As FileSystemEventArgs)
    lf.WriteLine(Now.ToShortDateString & "-" & Now.ToShortTimeString & "-" & e.FullPath & "-created")
End Sub

Public Sub file_changed(ByVal obj As Object, ByVal e As FileSystemEventArgs)
    lf.WriteLine(Now.ToShortDateString & "-" & Now.ToShortTimeString & "-" & e.FullPath & "-changed")
End Sub

Public Sub file_deleted(ByVal obj As Object, ByVal e As FileSystemEventArgs)
    lf.WriteLine(Now.ToShortDateString & "-" & Now.ToShortTimeString & "-" & e.FullPath & "-deleted")
End Sub

Protected Overrides Sub OnStop()
    lf.Close() 
End Sub
End Class

i have the ServiceName set to fswService (same as class name). When I added an installer I also set the ServiceName for the ServiceInstaller1 as fswService.

I want to start this service at runtime based on the user setting the path of the folder to be watched. To achieve this I have the following:

Dim fsw_controller As New ServiceProcess.ServiceController
fsw_controller.Start(fswService)

2 problems: first, intellisense error saying: 'fswService' is a type and cannot be used as an expression. second, I can not figure out a way to pass on to the service the path of the folder to watch (which is stored at My.Settings.userPath).

I really thought this is how you start a service. Am I missing something?

Your help is, as always, appreciated. Thanks

© Stack Overflow or respective owner

Related posts about vb.net

Related posts about windowsservice