title: Change Windows Service user programmatically
body: <p>I need to change Logon user for a Windows service programmatically. And I am using the following code to do that:</p>
  
  <pre><code>string objPath = string.Format("Win32_Service.Name='{0}'", ServiceName);
  using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
  {
  object[] wmiParams = new object[11];
  
  if (PredefinedAccount)
      {
          wmiParams[6] = "LocalSystem";
              wmiParams[7] = "";
      }
      else
      {
          wmiParams[6] = ServiceUsername; // provided by user
              wmiParams[7] = ServicePassword; // provided by user
      }
  
      object invokeResult = service.InvokeMethod("Change", wmiParams);
  
  // handle invokeResult - no error up to this point
  }
  </code></pre>
  
  <p>This code works in 90% of situations, but in some situations service cannot be started due to logon failure. There is usually no error on InvokeMetod but when we try to start the service we get the following error: </p>
  
  <blockquote>
    <p>System.InvalidOperationException: Cannot start service X on computer
    '.'. --> System.ComponentModel.Win32Exception: The service did not
    start due to a logon failure.</p>
  </blockquote>
  
  <p>The workaround solution is simple, we just need to enter the same credentials via Windows interface and problem is solved.</p>
  
  <p>So my question is, has anybody experienced the similar problem with ManagementObject because it seems that in some situation it does not relate Username and password to windows service? </p>