我有以下代码来检查Windows服务是否存在,但如果该服务不存在,它会不断抛出异常。
Dim controller As New ServiceController("test")
If controller.Status = Nothing Then
Label2.Text = ""
Else
ListBox1.Items.Add("Service found")
End If
如果找不到,我想要的是什么都不做,如果找到则添加到列表框。
答案 0 :(得分:4)
这可能是设计的,因为ServiceController旨在“连接并控制现有服务的行为”#34; (c.f。here)。如果服务不存在,则读取here Status
属性应该抛出InvalidOperationException
。
你可以做的是使用GetServices()method列出机器上的服务,看看你要找的东西是否存在 - 可能是这样的:
Dim servicesButNotDevices As ServiceController() = ServiceController.GetServices()
For Each service As ServiceController In servicesButNotDevices
If service.ServiceName = "my service name" Then 'May also use DispalyName property depending on your use case
'Put in list box
Exit For
End If
Next
如果您不想捕获并处理异常
答案 1 :(得分:2)
根据the ServiceController
documentation,这是预期的行为。如果服务存在,构造函数将创建一个ServiceController
实例,该实例提供控制服务的接口。如果该服务不存在,则无需执行任何操作,构造函数将抛出ArgumentException
。
以下代码应该满足您的需求:
Try
Dim controller As New ServiceController("test")
ListBox1.Items.Add("Service found")
Catch ex As ArgumentException
Label2.Text = ""
End Try
答案 2 :(得分:1)
感谢大家对此的投入。
我使用了NOVI的想法,但稍稍调整了一下:
For Each service As ServiceController In ServiceController.GetServices()
Dim serviceName As String = service.ServiceName
If serviceName = "mmg" Then
ListBox1.Items.Add(serviceName)
End If
Next
答案 3 :(得分:1)
Public Shared Function GetService() As ServiceProcess.ServiceController
Try
Dim Services = (From f In ServiceProcess.ServiceController.GetServices Select f Where f.ServiceName = "BilgiSoft").ToList
If Services.Count = 1 Then
Return Services(0)
Exit Function
Else
Return Nothing
Exit Function
End If
Catch ex As Exception
Return Nothing
Exit Function
End Try
End Function