在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