在Web上搜索信息後,我設法創建了一項服務,根據命令行,它可以安裝或卸載自身,或者僅作爲應用程序運行。以編程方式從.NET卸載Windows服務
但是,卸載代碼無法正常工作。
相關的代碼:
Private Function UnInstallService(ByVal args As String(), ByRef errMsg As String) As Boolean
Dim si As New ServiceInfo
If (Not GetServiceInfo(args, si)) Then
errMsg = "Error..."
Return False
End If
If (Not IsServiceInstalled(si.Name)) Then
errMsg = "Error..."
Return False
End If
Try
Dim installer As ServiceProcessInstaller = GetServiceInstaller(si)
Dim stateSaver As IDictionary = New Hashtable
Try
installer.Uninstall(stateSaver)
Catch e As exception
errMsg = "Error..."
Return False
End Try
Catch e As exception
errMsg = "Error..."
Return False
End Try
End Function
Private Function GetServiceInstaller(ByVal si As ServiceInfo) As ServiceProcessInstaller
Dim installer As ServiceInstaller = New ServiceInstaller()
Dim pInstaller As New ServiceProcessInstaller
pInstaller.Context = New InstallContext("", si.CommandLine)
installer.Description = si.Description
installer.DisplayName = si.DisplayName
installer.ServiceName = si.Name
installer.StartType = ServiceStartMode.Automatic
If (si.Account = "LocalSystem") Then
pInstaller.Account = ServiceAccount.LocalSystem
ElseIf (si.Account = "LocalService") Then
pInstaller.Account = ServiceAccount.LocalService
ElseIf (si.Account = "NetworkService") Then
pInstaller.Account = ServiceAccount.NetworkService
Else
pInstaller.Account = ServiceAccount.User
pInstaller.Password = si.Password
pInstaller.Username = si.Account
End If
pInstaller.Context.Parameters("assemblypath") = si.FullPath
pInstaller.Installers.Add(installer)
installer.Parent = pInstaller
Return pInstaller
End Function
它拋出一個NullReferenceException在調用installer.Uninstall 安裝的代碼是完全一樣的,除了檢查是否已安裝的服務,並調用installer.Install然後安裝程序。提交而不是卸載。我通過它完全相同的參數。
有什麼想法?
那麼,根據MSDN:「這種方法支持是.NET Framework基礎結構,不能直接在代碼中使用。「 http://msdn.microsoft.com/en-us/library/system.configuration.install.managedinstallerclass.installhelper%28v=VS.80%29.aspx無論如何,我會仔細看看它。謝謝! – raven 2010-09-09 08:56:07