如何安装以管理员身份运行的Windows服务?

Mik*_*ras 4 .net windows-services admin-rights

我编写了一个安装程序来安装需要启动/停止其他服务(B)的Windows服务(A).但是,当A尝试启动/停止B时,我得到以下异常:

System.InvalidOperationException:无法在计算机'.'上打开MyService服务.---> System.ComponentModel.Win32Exception:访问被拒绝

安装程序将服务作为本地服务安装,并通过我授予的UAC弹出窗口请求管理员权限.我还在设置为要求管理员权限的服务中添加了app.manifest文件:

但我仍然得到那个错误.

这就是我启动服务的方式(停止是相同的,当然除了它调用Stop):

using (Mutex mutex = new Mutex(false, "MyServiceLock"))
{
    mutex.WaitOne();

    if (ServiceExists(serviceName) == true)
    {
        using (ServiceController serviceController = new ServiceController(serviceName, "."))
        {
            serviceController.Start(); // this line throws the exception
        }
    }

    mutex.ReleaseMutex();
}
Run Code Online (Sandbox Code Playgroud)

为什么可以拒绝访问此服务?

Han*_*ant 8

服务不能要求UAC提升.听起来,您描述的UAC提示实际上是由安装程序而不是服务请求的.服务通常使用特权帐户运行,默认情况下为LocalSystem.请确保将服务配置为使用此特权帐户,而不是受限制的用户帐户.

  • 安装为LocalSystem(而不是LocalService)就可以了.谢谢! (2认同)