John
John

Reputation: 6648

Determining whether a service is already installed

As part of installing my windows service I have coded 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 intall it. I determing whether this needs doing by detecting whether it starts successfully. I anticipate delay between requesting it start and it actually setting it's RunningOk flag and would rather a generic, programmatic solution. The ( How to install a windows service programmatically in C#? ) http://dl.dropbox.com/u/152585/ServiceInstaller.cs solution is nearly 3 years old, long, and imports DLL's which from the little I know about .NET seems to defeat its security intentions.

Hence I would like to know of a more concise way to do this with .NET, if one exists?

Upvotes: 5

Views: 6347

Answers (2)

John
John

Reputation: 6648

To find a service, and whether it is running,

    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 it actually checks whether it is not stopped instead of whether it is running, but you can change that if you wish.

Nice to do this in concise .NET constructs. Don't recall where I got the info from but it looks so easy now and worth a post.

Upvotes: 11

Cosmin
Cosmin

Reputation: 21416

I recommend using the Windows Installer native support.

You can manage the service install, uninstall and start or stop operations.

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

Upvotes: 3

Related Questions