Win32Exception: 指定的服务不作为已安装的服务存在

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

我正在处理 windows 服务。在 catch 中阻止在停止服务时出现异常。

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

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

这是我的代码

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

如何检查服务是否安装?

您从 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;
    }