0

I am trying to run an exe file as window service. I have done it before manually by doing like this:

sc create TestService binPath= "C:\MyExePathWhichIsToBeRunAsWindowService" 

and it could worked properly, when i see the services i am able to find it, Now have to do the same using c# code.

The code should ask the user for the path of exe file and this file has to be run as window service and also the name which he has to provide to this window service.So these two things user will enter at runtime, which is an easy task for me but once if i got that, then how i will run the command below from c# code ?

sc create TestServiceNameUsrEntered binPath= "path user entered for exe at run time" 

Could some one please help me ?

EDIT: Please note that user will always enter serviceApplication exe file Not arbitrary files

struggling
  • 535
  • 1
  • 10
  • 25

2 Answers2

1

You can take a look at Topshelf.

If you like to do it from scratch yourself, you can take a look into the HostInstaller.cs, where it simply adds the needed registry key:

using (RegistryKey system = Registry.LocalMachine.OpenSubKey("System"))
using (RegistryKey currentControlSet = system.OpenSubKey("CurrentControlSet"))
using (RegistryKey services = currentControlSet.OpenSubKey("Services"))
using (RegistryKey service = services.OpenSubKey(_settings.ServiceName, true))
{
    service.SetValue("Description", _settings.Description);

    var imagePath = (string)service.GetValue("ImagePath");

    _log.DebugFormat("Service path: {0}", imagePath);

    imagePath += _arguments;

    _log.DebugFormat("Image path: {0}", imagePath);

    service.SetValue("ImagePath", imagePath);
}
Oliver
  • 43,366
  • 8
  • 94
  • 151
1

You should look into Process.Start. You might want to try something like this:

Process.Start("sc", String.Format("create \"{0}\" binPath=\"{1}\"", serviceName, binPath));
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139