SoFunction
Updated on 2025-03-07

C# Modify the username and password of the account in Windows

In C#, we can use Win32_Service in the WMI class or the function ChangeServiceConfig in the Win32 API to modify the username and password of the Windows service login identity (account) on the local or remote computer.

1. Use Win32 API to modify the service login identity information:

Using the function ChangeServiceConfig in the Win32 API, what is changed is the configuration information of the specified service in the Service Control Manager database.

private const int SC_MANAGER_ALL_ACCESS = 0x000F003F;
private const uint SERVICE_NO_CHANGE = 0xffffffff; //This value can be found inprivate const uint SERVICE_QUERY_CONFIG = 0x00000001;
private const uint SERVICE_CHANGE_CONFIG = 0x00000002;
 
[DllImport("", CharSet = , SetLastError = true)]
public static extern Boolean ChangeServiceConfig(IntPtr hService, UInt32 nServiceType, 
  UInt32 nStartType,UInt32 nErrorControl,String lpBinaryPathName,String lpLoadOrderGroup,
  IntPtr lpdwTagId, [In] char[] lpDependencies, String lpServiceStartName, 
  String lpPassword, String lpDisplayName);
 
[DllImport("", SetLastError = true, CharSet = )]
static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess);
 
[DllImport("", EntryPoint = "OpenSCManagerW", ExactSpelling = true, 
  CharSet = , SetLastError = true)]
public static extern IntPtr OpenSCManager(string machineName, string databaseName, uint dwAccess);
 
public static bool ChangeServiceAccountInfo(string serviceName, string username,string password)
{
  try
  {
    IntPtr scm_Handle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
    if (scm_Handle == )
     throw new ("Open Service Manager Error");
 
    IntPtr service_Handle = OpenService(scm_Handle, serviceName,SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);
    if (service_Handle == )
     throw new ("Open service error");
    //Modify the account username and password of the service    if (!ChangeServiceConfig(service_Handle, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, 
       SERVICE_NO_CHANGE, null, null, , null, username, password, null))
    {
      int nError = Marshal.GetLastWin32Error();
      Win32Exception win32Exception = new Win32Exception(nError);
      throw new ("Username and password for the service login identity cannot be modified:" + );
    }
    ("The service login identity information was modified successfully!");
    return true;
  }
  catch (Exception ex)
  {
    (());
    return false;
  }
}

2. Use WMI in C# to modify the service login identity information:

Using the WMI service, we need to add a reference.

Note: If your remote computer is connected to an Active Directory domain, use a fully qualified username (such as TestDomainMorgan) instead of a simple username (Morgan).

using ;

public static void ChangeServiceAccountInfobyWMI(string serviceName, string username, string password)
{
  string mgmntPath = ("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)("Change", accountParams);
    if (returnCode == 0)
    {
       ("The service login identity information was modified successfully!");
    }
    else
    {
       ("Service login identity information modification failed");
       ("Error code:" + returnCode);
       // This Microsoft official support link can view the corresponding return code message:       // /en-us/library/aa393660(v=vs.85).aspx
    }
  }
}

3. Use WMI in C# to modify the login identity information of the remote computer service:

With the WMI service, we need to add a reference and use administrator credentials when modifying service information in the remote computer.

Note: If your remote computer is connected to an Active Directory domain, use a fully qualified username (such as TestDomainMorgan) instead of a simple username (Morgan).

using ;
static void ChangeRemoteServiceAccountInfo(string remoteComputer, string serviceName, string username, string password)
{
  try
  {
    ConnectionOptions connectionOptions = new ConnectionOptions();
    // If necessary, please use the certificate    // = "Administrator";
    // = "AdminPassword";
    // = ;
    ManagementScope scope = new ManagementScope("\" + remoteComputer + "rootCIMV2", connectionOptions);
    ();
    string mgmntPath = ("Win32_Service.Name='{0}'", serviceName);
    using (ManagementObject service = new ManagementObject(scope, new ManagementPath(mgmntPath),new ObjectGetOptions()))
    {
      object[] accountParams = new object[11];
      accountParams[6] = username;
      accountParams[7] = password;
      uint returnCode = (uint)("Change", accountParams);
      if (returnCode == 0)
      {
        ("The service login identity information was modified successfully!");
      }
      else
      {
        ("Service login identity information modification failed");
        ("Error code:" + returnCode);
        // This Microsoft official support link can be viewed with the corresponding return code information:        // /en-us/library/aa393660(v=vs.85).aspx
      }
    }
  }
  catch (Exception ex)
  {
    (());
  }
}

The above is the detailed content of changing the username and password of the account in Windows by C#. For more information about changing the username and password in C#, please follow my other related articles!