.net – 获取Windows服务启动类型?

前端之家收集整理的这篇文章主要介绍了.net – 获取Windows服务启动类型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在System.ServiceProcess命名空间中,是否有任何类型的枚举或其他直接成员来确定ServiceController的服务的启动类型(自动,延迟自动,按需,禁用)?

我的想法是使用.NET框架类库的该命名空间(或其他命名空间)的可用成员来确定该事物,而不是查看操作系统注册表或WMI以获取服务的启动类型,因为我可以这样做,我我只是问.NET框架是否公开了一种更简单的方法来确定那件事.

用VB.Net编写的伪代码,但我也可以管理C#方法

Public Shared Function GetStartType(ByVal svcName As String) As ServiceControllerStatus

    Dim svc As ServiceController = (From service As ServiceController In ServiceController.GetServices()
         Where service.ServiceName.Equals(svcName,StringComparison.OrdinalIgnoreCase)
        ).FirstOrDefault

    If svc Is Nothing Then
        Throw New ArgumentException("Any service found with the specified name.","svcName")
    Else
        Using svc
            ' Note that StartTypeEnumValue does not exists.
            Return svc.StartTypeEnumValue
        End Using
    End If

End Function
您可以使用WMI和 ManagementObject来实现此目标,基于 C# – Get Startup Type of a Service (Windows).

像这样的东西(基于链接文章中的代码).最初的例子是在C#中,所以我试图快速转换到VB.NET,但语法可能有点不对.我还将方法返回类型修改为String,因为我一旦得到它就不确定你想要对该值做什么.

不要忘记添加Imports System.Management.

Public Shared Function GetStartType(ByVal svcName As String) As String

    Dim startMode As String = String.Empty
    Dim filter As String = String.Format("SELECT StartMode FROM Win32_Service WHERE Name = '{0}'",svcName)
    Dim svc As ManagementObjectSearcher = New ManagementObjectSearcher(filter)

    If svc Is Nothing Then
        Throw New ArgumentException("Any service found with the specified name.",paramName:="svcName")
    Else
        Try
            Dim services As ManagementObjectCollection = svc.Get()

            For Each service As ManagementObject In services
                startMode = service.GetPropertyValue("StartMode").ToString()
            Next
        Catch ex As Exception
            ' Do something if needed
        End Try
    End If

    Return StartMode
End Function

猜你在找的Windows相关文章