Determining if a service is installed

As part of installing my Windows service, I encoded an alternative to installutil and the command line:

IDictionary state = new Hashtable();
using (AssemblyInstaller inst = new AssemblyInstaller(typeof(MyServiceClass).Assembly, args))
{
    IDictionary state = new Hashtable();
    inst.UseNewContext = true;
    //# Service Account Information
    inst.Install(state);
    inst.Commit(state);
}

to develop it. I determine if this should be done by detecting if it starts successfully. I expect a delay between the request to launch it and the actual setting of the RunningOk flag and rather a universal software solution. ( How to install a Windows software product programmatically in C #? ) Http://dl.dropbox.com/u/152585/ServiceInstaller.cs solution is almost 3 years long and imports a DLL, which, as I know, about .NET, as if triumphing in his security intentions.

Therefore, I would like to know a shorter way to do this with .NET, if it exists?

+5
source share
2 answers

To find a service and if it works,

    private static bool IsServiceInstalled(string serviceName)
    {
        ServiceController[] services = ServiceController.GetServices();
        foreach (ServiceController service in services)
            if (service.ServiceName == serviceName) return true;
        return false;
    }

    private static bool IsServiceInstalledAndRunning(string serviceName)
    {
        ServiceController[] services = ServiceController.GetServices();
        foreach (ServiceController service in services)
            if (service.ServiceName == serviceName) return service.Status != ServiceControllerStatus.Stopped;
        return false;
    }

Note that it actually checks to see if it is stopped and not working, but you can change this if you want.

This is nice to do in compressed .NET constructs. Do not remember where I got the information from, but now it looks so simple and worth publishing.

+11
source

I recommend using the native Windows Installer support .

You can control the installation, removal, and start or stop of the service.

Unfortunately, not all scripting tools offer direct support for this, so you will need to find one that does.

+3

All Articles