【问题标题】:What is the best way to change the credentials of a Windows service using C#使用 C# 更改 Windows 服务凭据的最佳方法是什么
【发布时间】:2008-09-24 07:41:28
【问题描述】:

我需要使用 C# 更改现有 Windows 服务的凭据。我知道这样做有两种不同的方式。

  1. ChangeServiceConfig,见ChangeServiceConfig on pinvoke.net
  2. ManagementObject.InvokeMethod 使用 Change 作为方法名。

这似乎不是一种非常“友好”的方式,我想知道我是否错过了另一种更好的方式。

【问题讨论】:

    标签: .net configuration service


    【解决方案1】:

    这是一种使用 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);
          }
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      ChangeServiceConfig 是我过去的做法。 WMI 可能有点不稳定,我只有在别无选择时才想使用它,尤其是在访问远程计算机时。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-16
        • 1970-01-01
        • 2020-11-03
        • 1970-01-01
        • 2013-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多