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



我有一个配置程序和一组按配置的设备运行的服务。在我的配置程序中,当添加要监控的设备时,我会使用以下内容创建一个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 PathProject NameMyService.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)

最新更新