使用C#更改Windows服务的凭据的最佳方法是什么
时间:2020-03-06 14:38:51 来源:igfitidea点击:
我需要使用C#更改现有Windows服务的凭据。我知道有两种不同的方法可以做到这一点。
- ChangeServiceConfig,请参见pinvoke.net上的ChangeServiceConfig
- 使用Change作为方法名称的ManagementObject.InvokeMethod。
两者似乎都不是一种非常"友好"的方式,我想知道我是否正在错过另一种更好的方式。
解决方案
这是使用System.Management类的一种快速而肮脏的方法。
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); } } } }
ChangeServiceConfig是我过去所做的方式。 WMI可能有点不稳定,我只想在没有其他选择的情况下才使用它,尤其是在访问远程计算机时。