开发者

Managed API for changing service paths

I have a Windows Service installed on a machine.

In a new release, I've renamed the services .exe name (e.g., MyService.exe -> Foo.Server.exe).

I understand service executable paths can be changed by modifying the registry, but does a managed API exis开发者_JS百科t so that I can be more confident it won't break in future releases?


You can PInvoke the SCM API, ChangeServiceConfig, and provide the lpBinaryPathName parameter.

Here is the PInvoke prototype from: http://pinvoke.net/default.aspx/advapi32/ChangeServiceConfig.html

[DllImport("Advapi32.dll", EntryPoint="ChangeServiceConfigW", CharSet=CharSet.Unicode, ExactSpelling=true, SetLastError=true)]
internal static extern bool ChangeServiceConfig(
    SafeHandle hService,
    int dwServiceType, 
    int dwStartType, 
    int dwErrorControl, 
    [In] string lpBinaryPathName,
    [In] string lpLoadOrderGroup, 
    IntPtr lpdwTagId,
    [In] string lpDependencies, 
    [In] string lpServiceStartName, 
    [In] string lpPassWord, 
    [In] string lpDisplayName
);

Using the ServiceController class to open the SCM and service you just call it like this:

static void ChangeServicePath(string svcName, string exePath)
{
    const int SERVICE_NO_CHANGE = -1;
    using (ServiceController control = new ServiceController(svcName))
        ChangeServiceConfig(control.ServiceHandle,
                            SERVICE_NO_CHANGE,
                            SERVICE_NO_CHANGE,
                            SERVICE_NO_CHANGE,
                            exePath,
                            null,
                            IntPtr.Zero,
                            null,
                            null,
                            null,
                            null);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜