'Can Windows Service change its own password on start?

Question: Is it possible to update the password for the windows service during startup of that windows service (in the C# implementation of the windows service)?

Background: We store passwords in the vault. We have also windows service using accounts with password to log on. As the passwords change periodically, I'd like to query the vault to check if password has changed and if so, update the password for the windows service. I'd like to do that every time the windows service is started.

I used the following method to update the password of the windows service from a separate console application (from https://morgantechspace.com/2015/03/csharp-change-service-account-username-and-password.html)

public static void ChangeServiceAccountInfobyWMI(string serviceName, string username,
      string password)
{
string mgmntPath = string.Format("Win32_Service.Name='{0}'", serviceName);
using (ManagementObject service = new ManagementObject(new ManagementPath(mgmntPath)))
{
    object[] accountParams = new object[11];
    accountParams[6] = username;
    accountParams[7] = password;
    uint returnCode = (uint)service.InvokeMethod("Change", accountParams);
    if (returnCode == 0)
    {
         Console.WriteLine("Service account information changed successfully");
    }
    else
    {
         Console.WriteLine("Failed to change Service account information");
         Console.WriteLine("Error code: " + returnCode);
         // Support link to check the message for corresponding Return code:
         // https://msdn.microsoft.com/en-us/library/aa393660(v=vs.85).aspx
    }
}
}

However, I cannot apply that for the windows service startup. It looks like the first thing is the log on with already specified password and only later the password can be updated from the code.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source