【问题标题】:Object reference not set to an instance of an object when trying to unninstall a service c#尝试卸载服务时未将对象引用设置为对象的实例c#
【发布时间】:2016-08-01 22:34:54
【问题描述】:

我有以下代码可以停止和卸载服务。 它正确停止了服务,但是当我尝试卸载时它给了我这个错误:

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();
            }
        }
    }

【问题讨论】:

    标签: c# object reference


    【解决方案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 中提到的方法。

    【讨论】:

      猜你喜欢
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多