Search code examples
c#windowswindows-services

Win32Exception: The specified service does not exist as an installed service


I am working on windows service. In catch block getting exception while stopping service.

System.InvalidOperationException: 'Service AirService was not found on computer'

InnerException- Win32Exception: The specified service does not exist as an installed service.

This is my code

catch (Exception ex)
{
    //WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
    //Stop the Windows Service.
    using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("AirService"))
    {
        serviceController.Stop();
    }
}

How can I check if service installed or not?


Solution

  • You get a list of installed services from ServiceController.GetServices().

        public static bool CheckServiceInstalled(string serviceToFind)
        {
            ServiceController[] servicelist = ServiceController.GetServices();
            foreach (ServiceController service in servicelist)
            {
                if (service.ServiceName == serviceToFind)
                    return true;
            }
            return false;
        }