我需要使用C#来改变现有的Windows服务的凭据。我知道两个不同的这样做的方式。
I need to change the credentials of an already existing Windows service using C#. I am aware of two different ways of doing this.
ChangeServiceConfig,请参见 ChangeServiceConfig上pinvoke.net 在使用更改的方法名ManagementObject.InvokeMethod。似乎都不这样做的一个非常友好的方式,我在想,如果我缺少另一种更好的方式来做到这一点。
Neither seems a very "friendly" way of doing this and I was wondering if I am missing another and better way to do this.
下面是一个使用System.Management类之一快速和肮脏的方法。
Here is one quick and dirty method using the System.Management classes.
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace ServiceTest
{
class Program
{
static void Main(string[] args)
{
string theServiceName = "My Windows Service";
string objectPath = string.Format("Win32_Service.Name='{0}'", theServiceName);
using (ManagementObject mngService = new ManagementObject(new ManagementPath(objectPath)))
{
object[] wmiParameters = new object[11];
wmiParameters[6] = @"domain\username";
wmiParameters[7] = "password";
mngService.InvokeMethod("Change", wmiParameters);
}
}
}
}