views:

400

answers:

3

I need to change the credentials of an already existing Windows service using C#. I am aware of two different ways of doing this.

  1. ChangeServiceConfig, see ttp://www.pinvoke.net/default.aspx/advapi32.ChangeServiceConfig
  2. ManagementObject.InvokeMethod using Change as the method name.

Neither seems a very "friendly" way of doing this and I was wondering if I am missing another and better way to do this.

A: 

I guess the lack of an answer means there is no better way :-(

In that case ChangeServiceConfig would probably be the best way.

Maurice
Hey, stackoverflow is not instant messaging, so lack of an answer in 3 hours doesn't mean that nobody will answer it. Wait for a couple of days, maybe a week and only then you can say, that there were no answers.
Kasprzol
+2  A: 

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);
      }
    }
  }
}
Magnus Johansson
+1  A: 

ChangeServiceConfig is the way that I've done it in the past. WMI can be a bit flaky and I only ever want to use it when I have no other option, especially when going to a remote computer.

Adam Ruth