2010-05-27 26 views
1

我有以下窗口服務文件:vb.net如何在運行時啓動文件夾監視器服務並傳遞文件夾路徑以進行監視?

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 

我有服務名稱設置爲fswService(與類名)。當我添加安裝程序時,我還將ServiceInstaller1的ServiceName設置爲fswService。

我想在運行時根據用戶設置要觀看的文件夾的路徑啓動此服務。爲了實現這一點,我有以下:

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

2問題:第一,智能感知錯誤說:「fswService」是一種類型的,不能用作表達式。第二,我無法想出一種方法來傳遞文件夾的路徑(存儲在My.Settings.userPath中)的路徑。

我真的認爲這是你如何開始一項服務。我錯過了什麼嗎?

我們一如既往的讚賞您的幫助。 謝謝

+0

好的。我想出了第一部分 昏暗的fsw_controller作爲新的ServiceController(「fswService」) fsw_controller.Start() 但我仍然不知道如何傳遞文件夾的路徑來觀看。任何幫助? – mazrabul 2010-05-27 22:41:41

回答

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 '.'. 

任何幫助嗎?請...

+0

我認爲這個問題是您在使用Application.StartupPath用,我的版本可與Path.Combine( Path.GetDirectoryName( Assembly.GetEntryAssembly()。地點 ), 「fsw_lg.log」) 還fsw.Filter = 「.txt」可能需要fsw.Filter =「* .txt」 – 2012-07-28 17:16:18

0

您只能通過ServiceController.ExecuteCommand過程發送一個整數值(128-255之間)。然後重寫Windows Service中的OnCustomCommand事件,該事件在ExecuteCommand發送到該特定服務時運行。我會將要觀看的文件夾的名稱保存在一個文本文件中,然後讓OnCustomCommand事件查看該文件夾的文件。您可能會遇到該錯誤,因爲您在Windows服務已經運行時運行了ServiceController的啓動過程。要更新ServiceController.Status屬性,請運行StatusController.Refresh()過程。