Visual Studio - 启动/停止具有空格的Windows服务名称

时间:2016-06-08 11:37:18

标签: .net vb.net service

我正在修改下面的代码来启动/停止FileZilla Server。我遇到的问题是服务名称中包含空格。当我在命令提示符下使用sc start FileZilla Server时,它需要双引号(sc start" FileZilla Server")。当然,当我传递代码时:

Dim sc As New ServiceController("FileZilla Server")

它没有留下引号,所以我得知服务在系统上不存在的错误。如果我逃避引号如:

Dim sc As New ServiceController("""FileZilla Server""")

我得到了同样的错误,即使通过调试我可以看到服务名称是用引号传递的。我已经确认在命令提示符下键入引号是有效的,并且传递由一个单词组成的服务名称。知道如何让这个工作吗?

' If it is started (running, paused, etc), stop the service.
' If it is stopped, start the service.
Dim sc As New ServiceController("""FileZilla Server""")
Console.WriteLine("The FileZilla service status is currently set to {0}", sc.Status)

If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then
   ' Start the service if the current status is stopped.
   Console.WriteLine("Starting the FileZilla service...")
   sc.Start()
Else
   ' Stop the service if its status is not set to "Stopped".
   Console.WriteLine("Stopping the FileZilla service...")
   sc.Stop()
End If

' Refresh and display the current service status.
sc.Refresh()
Console.WriteLine("The FileZilla service status is now set to {0}.", sc.Status)

1 个答案:

答案 0 :(得分:1)

服务的显示名称和实际名称可以不同。例如:

enter image description here

所以你可以从服务中找到服务名称并使用它......

但您可以从显示名称中找到服务,如下所示:

'this requires a reference to system.ServiceProcess adding
Dim sc = System.ServiceProcess.ServiceController.GetServices.FirstOrDefault(Function(x) x.DisplayName = "FileZilla Server FTP server")
If sc Is Nothing Then Return

这些都适用于我:

    Dim sc = System.ServiceProcess.ServiceController.GetServices.FirstOrDefault(Function(x) x.ServiceName = "FileZilla Server")

    Dim sc = System.ServiceProcess.ServiceController.GetServices.FirstOrDefault(Function(x) x.DisplayName = "FileZilla Server FTP server")