I would lke to programmatically enable and start the Net.Tcp Port Sharing Service in C#. I can easily start the service using the ServiceController class. However, how do I enable the service, which is disabled by default?
I found one recommendation online to set the following registry key to 2 as follows, which supposedly sets the service startup type to Automatic:
string path = "SYSTEM\\CurrentControlSet\\Services\\" + serviceName;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path, true)) {
key.SetValue("Start", 2);
}
I tried this and while it did appear to change the startup type to Automatic, there must be more to it, as the service would not now start up (programmatically or manually). I had to reset the startup type manually through the services.msc to reset things, so that the service could be enabled and started up again.
Has anyone solved this?
There is more than one way to do this, depending on how “pure” of a solution you want. Here are some options. Note that all of these solutions require administrative rights and must run in an elevated process.
Use the command prompt via C#
This will involve shelling out to
sc.exeand changing the startup type of the service via command line arguments. This is similar to the solution you mention above except there is no registry hacking required.Use WMI
This requires an assembly reference for
System.Management.dll. Here we will use WMI functionality toChangeStartModefor the service.Use P/Invoke to Win32 APIs
To some people, this is the most “pure” method, although it’s more tricky to get right. Basically you’ll want to call ChangeServiceConfig from .NET. However, this requires that you first call OpenService for the specified service and that requires calling OpenSCManager beforehand (and don’t forget to CloseServiceHandle when you’re done!).
Note: This code is for demonstration purposes only. It does not contain any error handling and may leak resources. A proper implementation should use
SafeHandletypes to ensure proper cleanup and should add appropriate error checking.