我有以下代码来停止和取消安装服务。 它会正确停止服务,但在我尝试卸载时会出现此错误:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Configuration.Install.Installer.Uninstall(IDictionary savedState)
at System.ServiceProcess.ServiceInstaller.Uninstall(IDictionary savedState)
at UpdateOrca.FuncoesUpdater.StopService(String serviceName, Int32 timeoutMilliseconds, Boolean Unninstall) in C:\Users\me\Downloads\UpdateOrcaV2013\UpdateOrca\UpdateOrca\FuncoesUpdater.cs:line 165
代码:
public void StopService(string serviceName, int timeoutMilliseconds, bool Unninstall)
{
if (ServicoInstalado(serviceName) == true) //&& ServiceRunning(serviceName) == true
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
if (Unninstall == true)
{
ServiceInstallerObj.ServiceName = serviceName;
ServiceInstallerObj.Uninstall(null); (LINE OF THE ERROR)
}
}
catch (Exception ex)
{
Program.Erro = ex.ToString();
Erro NewErro = new Erro();
NewErro.ShowDialog();
}
}
}
答案 0 :(得分:1)
ServiceInstaller.Uninstall()
方法实际上需要某种类型的关于卸载内容的上下文信息。这通常可以作为IDictionary
对象传递给Uninstall()
方法,但如果您决定通过null
,则可能需要明确设置上下文:
// Build your uninstaller
ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
if (Unninstall)
{
// Set a context (using a specific file to log uninstall info)
ServiceInstallerObj.Context = new InstallContext("{path-to-log-file}", null);
// Continue setting your service and uninstalling it
ServiceInstallerObj.ServiceName = serviceName;
ServiceInstallerObj.Uninstall(null);
}
如果这不起作用,您可以考虑尝试类似于this related discussion中提到的方法。