简体   繁体   English

修改Windows服务可执行文件的路径

[英]Modifying path to executable of windows service

I'm trying to write console application to change path to executable of windows service. 我正在尝试编写控制台应用程序以将路径更改为Windows服务的可执行文件。 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. 我在这里https://msdn.microsoft.com/zh-cn/en-en/library/system.diagnostics.process(v=vs.110).aspx找到了一些有趣的信息,但它也没有帮助我。

If you can't just call sc.exe to do it, you can use the interop code from this answer and add as follows: 如果您不能只调用sc.exe来执行此操作,则可以使用此答案中的互操作代码并添加如下内容:

    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. 按照sc.exe此代码需要管理员权限才能打开SCM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM