使用C#更改Windows服务凭据的最佳方法是什么?

Mau*_*ice 6 .net service configuration

我需要使用C#更改已存在的Windows服务的凭据.我知道有两种不同的方法.

  1. ChangeServiceConfig,请参阅pinvoke.net上的ChangeServiceConfig
  2. ManagementObject.InvokeMethod使用Change作为方法名称.

这似乎都不是一种非常"友好"的方式,我想知道我是否错过了另一种更好的方法来做到这一点.

Mag*_*son 6

下面是一个使用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);
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)