Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
John Avatar asked Sep 11 '11 21:09

John


People also ask

How do you check Windows service is installed or not?

Right-click My Computer, found on the Windows desktop or in the Start menu. Select Properties in the popup menu. In the System Properties window, under the General tab, the version of Windows is displayed, and the currently-installed Windows Service Pack.


1 Answers

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.

like image 116
John Avatar answered Sep 28 '22 09:09

John