尝试从 VB.Net 应用程序以编程方式安装服务 - 调用 SC.exe 失败

Trying to install service programatically from VB.Net application - Calls to SC.exe fail

我有一个配置程序和一堆服务,每个配置的设备 运行。在我的配置程序中,当添加要监视的设备时,我使用类似这样的 ID 创建一个服务:

Dim appPath As String = IO.Path.GetDirectoryName(Application.ExecutablePath)
Dim servicePath As String = appPath & "\MyService.exe"
Dim serviceName As String = "MyService-" & DeviceID
Dim createCommand As String = "sc.exe create " & serviceName & " binpath= " & Chr(34) & servicePath & " " & mySiteID & Chr(34) & " type= share start= demand"
Process.Start(createCommand)

因此,当所有内容组合在一起时,它看起来像这样:

sc create MyService-253 binpath= "C:\Some Path\Project Name\MyService.exe 253" type= share start= demand

问题是没有创建服务。进程命令抛出“系统找不到指定的文件”。

程序(和 VS)运行正在作为管理员。此外,复制和粘贴 createCommand 变量的内容确实可以正确创建服务。因此,如果我手动 运行 应该是 运行 的相同命令,它会创建服务并且服务正常工作。我错过了什么?

您不能像那样将完整的命令行传递给 Process.Start。如果您阅读了该方法的文档,那么您就会知道您需要分别传递文件路径和命令行参数,例如

Dim appPath = Path.GetDirectoryName(Application.ExecutablePath)
Dim servicePath = Path.Combine(appPath, "MyService.exe")
Dim serviceName = "MyService-" & DeviceID
Dim fileName = "sc.exe"
Dim arguments = $"create {serviceName} binpath= ""{servicePath} {mySiteID}"" type= share start= demand"
Process.Start(fileName, arguments)