1
我在機器上安裝了Windows服務。用於更改服務路徑的託管API
在新版本中,我重命名了服務.exe名稱(例如,MyService.exe
- >Foo.Server.exe
)。
我明白服務可執行文件路徑可以被modifying the registry更改,但是是否存在託管API,以便我可以更有信心在未來的版本中不會中斷?
我在機器上安裝了Windows服務。用於更改服務路徑的託管API
在新版本中,我重命名了服務.exe名稱(例如,MyService.exe
- >Foo.Server.exe
)。
我明白服務可執行文件路徑可以被modifying the registry更改,但是是否存在託管API,以便我可以更有信心在未來的版本中不會中斷?
您可以PInvoke SCM API ChangeServiceConfig,並提供lpBinaryPathName參數。
下面是從PInvoke的原型: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
);
使用ServiceController類打開SCM和服務,你只需要調用它像這樣:
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);
}
注:可能需要使用一個「使用「圍繞control.ServiceHandle,因爲它總是返回一個新的副本。這樣你就可以依靠GC來完成新的副本。 –