Reputation: 41
I'm trying to write console application to change path to executable of windows service. More exactly it should take service name as argument then change service path to executable to given. Unfortunately I cannot find any information how to achieve that, maybe someone with more experience could give any advice?
I found some interesting info here https://msdn.microsoft.com/en-us/en-en/library/system.diagnostics.process(v=vs.110).aspx but it also didn't help me.
Upvotes: 1
Views: 5539
Reputation: 12270
If you can't just call sc.exe
to do it, you can use the interop code from this answer and add as follows:
public static void SetWindowsServicePath(string serviceName, string binPath)
{
IntPtr hManager = IntPtr.Zero;
IntPtr hService = IntPtr.Zero;
try
{
hManager = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
if (hManager == IntPtr.Zero)
{
ThrowWin32Exception();
}
hService = OpenService(hManager, serviceName, SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);
if (hService == IntPtr.Zero)
{
ThrowWin32Exception();
}
if (!ChangeServiceConfig(hService, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, binPath, null, IntPtr.Zero, null, null, null, null))
{
ThrowWin32Exception();
}
}
finally
{
if (hService != IntPtr.Zero) CloseServiceHandle(hService);
if (hManager != IntPtr.Zero) CloseServiceHandle(hManager);
}
}
As per sc.exe
this code needs admin rights in order to open the SCM.
Upvotes: 1