Search code examples
vb.netservicesc.exe

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


I have a config program and a bunch of services that run per configured device. In my config program when a device to monitor is added I create a service with a ID using something like this:

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)

So when it all comes together it looks something like this:

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

Problem is the service isn't being created. The process command is throwing a "The system cannot find the file specified".

The program (and VS) are running as a admin. Also copying and pasting the contents of the createCommand variable DOES work to correctly create the service. So if I manually run the same command that should be run it creates the service and the service works correctly. What am I missing?


Solution

  • You cannot pass a full commandline to Process.Start like that. If you had read the documentation for that method then you would know that you need to pass the file path and the commandline arguments separately, e.g.

    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)