1

I have the following code that stops and un-installs a service. It stops the service correctly but it gives me this error when I try to un-install:

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

Code:

    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();
            }
        }
    }
jDo
  • 3,962
  • 1
  • 11
  • 30
Mr.Toxy
  • 357
  • 4
  • 19

1 Answers1

1

The ServiceInstaller.Uninstall() method actually requires some type of context information about what you are uninstalling. This can generally be passed in as an IDictionary object to the Uninstall() method, but if you decide to pass null in instead, you'll probably need to set the context explicitly :

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

If that doesn't work, you may consider trying an approach similar to the one mentioned in this related discussion.

Community
  • 1
  • 1
Rion Williams
  • 74,820
  • 37
  • 200
  • 327