在网上搜索信息后,我设法创建了一个服务,根据命令行,可以自行安装或卸载,或者只是作为应用程序运行。
但是,卸载代码无法正常工作。
相关代码:
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
它在对installer.Uninstall的调用中抛出NullReferenceException 安装代码完全相同,除了检查服务是否已安装,并调用installer.Install然后安装installer.Commit而不是Uninstall。我传给它的参数完全相同。
有什么想法吗?
答案 0 :(得分:1)
您的代码似乎有点长,我所做的就是调用:
Dim path As String = Assembly.GetExecutingAssembly().Location
ManagedInstallerClass.InstallHelper(New String() {"/u", path})
安装我所做的就是:
Dim path As String = Assembly.GetExecutingAssembly().Location
ManagedInstallerClass.InstallHelper(New String() {path})
然后我在ProjectInstaller
的构造函数中设置了用户名等的代码
编辑:虽然请注意ManagedInstallerClass的文档有以下引用:此API支持.NET Framework基础结构,不能直接在您的代码中使用。
因此,从您自己的代码中使用它可能不是未来的证据......
答案 1 :(得分:1)
我在这里发现了问题: http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/58505d7b-cb78-4486-88fc-9b86890664e0
问题在于
行installer.Uninstall(stateSaver)
相反,应该是
installer.Uninstall(Nothing)