以编程方式更改Windows服务用户 [英] Change Windows Service user programmatically

查看:110
本文介绍了以编程方式更改Windows服务用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要改变登录用户的Windows服务编程。我现在用的是下面的code做到这一点:

I need to change Logon user for a Windows service programmatically. And I am using the following code to do that:

string objPath = string.Format("Win32_Service.Name='{0}'", ServiceName);
using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
{
object[] wmiParams = new object[11];

if (PredefinedAccount)
    {
        wmiParams[6] = "LocalSystem";
            wmiParams[7] = "";
    }
    else
    {
        wmiParams[6] = ServiceUsername; // provided by user
            wmiParams[7] = ServicePassword; // provided by user
    }

    object invokeResult = service.InvokeMethod("Change", wmiParams);

// handle invokeResult - no error up to this point
}

此code工作在90%的情况,但在某些情况下,服务不能启动由于登录失败。通常有上InvokeMetod没有错误,但是,当我们尝试启动,我们得到以下错误的服务:

This code works in 90% of situations, but in some situations service cannot be started due to logon failure. There is usually no error on InvokeMetod but when we try to start the service we get the following error:

System.InvalidOperationException:无法启动计算机X服务   。。 - > System.ComponentModel.Win32Exception:服务没有   启动由于登录失败。

System.InvalidOperationException: Cannot start service X on computer '.'. --> System.ComponentModel.Win32Exception: The service did not start due to a logon failure.

解决方法解决方法很简单,我们只需要通过Windows界面和问题解决进入相同的凭证。

The workaround solution is simple, we just need to enter the same credentials via Windows interface and problem is solved.

所以我的问题是,有没有人经历过类似的问题,因为的ManagementObject似乎在某些情况下,它并不涉及用户名和密码的窗口服务?

So my question is, has anybody experienced the similar problem with ManagementObject because it seems that in some situation it does not relate Username and password to windows service?

推荐答案

那么经过大量的测试,我们计算过,在大多数情况下,问题是由该的错误

Well after a lot of testing we figured that, in most cases the problem is caused by this bug.

这篇关于以编程方式更改Windows服务用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆