Imports System.ServiceProcess
Imports System.Configuration.Install
一、判断服务是否存在
Private Function ServiceIsExisted(ByVal ServiceName As String) As Boolean
Dim SV As ServiceController() = ServiceController.GetServices
Dim s As ServiceController
For Each s In SV
If s.ServiceName = ServiceName Then
Return True
Exit Function
End If
Next
Return False
End Function
二、制作安装服务
Private Sub InStallService(ByVal stateSaver As IDictionary, ByVal filepath As String)
Try
Dim cSN As String = "Service1"
Dim Service As ServiceController = New ServiceController(cSN)
If ServiceIsExisted(cSN) Then
MsgBox("服务已经存在")
Exit Sub
End If
Dim myAsIn As AssemblyInstaller = New AssemblyInstaller
myAsIn.UseNewContext = True
myAsIn.Path = filepath
myAsIn.Install(stateSaver)
myAsIn.Commit(stateSaver)
Service.Start()
MsgBox("安装成功")
Catch ex As Exception
MsgBox("发生错误" & ex.Message)
End Try
End Sub
三、删除安装服务
Private Sub UnStallService(ByVal stateSaver As IDictionary, ByVal filepath As String)
Try
Dim cSN As String = "Service1"
Dim Service As ServiceController = New ServiceController(cSN)
If Not ServiceIsExisted(cSN) Then
MsgBox("服务不存在")
Exit Sub
End If
Dim myAsIn As AssemblyInstaller = New AssemblyInstaller
myAsIn.UseNewContext = True
myAsIn.Path = filepath
myAsIn.Uninstall(stateSaver)
myAsIn.Dispose()
MsgBox("删除成功")
Catch ex As Exception
MsgBox("发生错误" & ex.Message)
End Try
End Sub
四、启动服务:
Private Sub StartService(ByVal cSN As String)
If ServiceIsExisted(cSN) Then
Dim service As ServiceController = New ServiceController(cSN)
If service.Status <> ServiceControllerStatus.Running Or service.Status <> ServiceControllerStatus.StartPending Then
service.Start()
Dim i As Int16
For i = 0 To 100
service.Refresh()
System.Threading.Thread.Sleep(1000)
If service.Status = ServiceControllerStatus.Running Then
Exit Sub
ElseIf i = 59 Then
Throw New Exception("startServiceError" & cSN)
End If
Next
End If
End If
End Sub
五、停止服务:
Private Sub StopService(ByVal cSN As String)
If ServiceIsExisted(cSN) Then
Dim Service As ServiceController = New ServiceController(cSN)
If Service.Status = ServiceControllerStatus.Running Then
Service.Stop()
Dim i As Int16
For i = 0 To 60
Service.Refresh()
System.Threading.Thread.Sleep(1000)
If Service.Status = ServiceControllerStatus.Stopped Then
Exit Sub
ElseIf i = 59 Then
Throw New Exception("stopServiceError:" & cSN)
End If
Next
End If
End If
End Sub