首页 > 解决方案 > Win32Exception:指定的服务不作为已安装的服务存在

问题描述

我正在开发 Windows 服务。在catch停止服务时阻止出现异常。

System.InvalidOperationException:“在计算机上未找到 Service AirService”

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

这是我的代码

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

如何检查服务是否已安装?

标签: c#windowswindows-services

解决方案


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

推荐阅读