我有以下Windows服务文件:
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
我将ServiceName设置为fswService(与类名相同)。当我添加安装程序时,我还将ServiceInstaller1的ServiceName设置为fswService。
我想在运行时根据用户设置要监视的文件夹的路径启动此服务。为实现这一目标,我有以下几点:
Dim fsw_controller As New ServiceProcess.ServiceController
fsw_controller.Start(fswService)
2个问题:首先,intellisense错误说:'fswService'是一个类型,不能用作表达式。第二,我无法找到一种方法将服务器传递给要监视的文件夹的路径(存储在My.Settings.userPath中)。
我真的以为这是你开始服务的方式。我错过了什么吗?
您的帮助一如既往地受到赞赏。 谢谢
答案 0 :(得分:0)
确定。我想我把它们都弄清楚,但是当我运行应用程序时出现错误。
在服务文件中我改变了
fsw.Path = args(0)
要
fsw.Path = My.Settings.userPath
要修复启动服务(正如我在评论中提到的那样),我做了:
Dim fsw_controller As New ServiceController("fswService")
fsw_controller.Start()
我重建了应用程序,使用installutil.exe重新安装了服务并运行它。但是我收到了一个错误:
InvalidOperationException was unhandled
Cannot start service fswService on computer '.'.
对此有何帮助?请..
答案 1 :(得分:0)
您只能通过ServiceController.ExecuteCommand过程发送一个整数值(介于128-255之间)。然后,您将覆盖Windows服务中的OnCustomCommand事件,该事件在将ExecuteCommand发送到该特定服务时运行。我会在文本文件中保存要监视的文件夹的名称,只是让OnCustomCommand事件查看该文件夹的文件。您可能会收到该错误,因为您在Windows服务已经运行时运行了ServiceController的Start过程。要更新ServiceController.Status属性,请运行StatusController.Refresh()过程。