Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change local administrator password in C#

Tags:

c#

wmi

I am looking for a way to change the password of a local user account (local Administrator) on a Windows (XP in this case) machine. I have read the CodeProject article about one way to do this, but this just doesn't seem 'clean'.

I can see that this is possible to do with WMI, so that might be the answer, but I can't figure out how to use the WinNT WMI namespace with ManagementObject. When I try the following code it throws an "Invalid Parameter" exception.

public static void ResetPassword(string computerName, string username, string newPassword){ 
            ManagementObject managementObject = new ManagementObject("WinNT://" + computerName + "/" + username); // Throws Exception
            object[] newpasswordObj = {newPassword};
            managementObject.InvokeMethod("SetPassword", newpasswordObj);
}

Is there a better way to do this? (I'm using .NET 3.5)

Edit: Thanks Ely for pointing me in the right direction. Here is the code I ended up using:

public static void ResetPassword(string computerName, string username, string newPassword) { 
        DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username)); 
        directoryEntry.Invoke("SetPassword", newPassword);
}
like image 613
Andy May Avatar asked Oct 24 '08 18:10

Andy May


People also ask

How do I change my local administrator password using cmd?

Open Start on Windows 10. Search for Command Prompt, right-click the top result, and select the Run as administrator option. In the command, make sure to change USERNAME with the account name you want to update. Type a new password and press Enter.

How do I reset local administrator password without login?

To open an elevated Command Prompt without logging in, you can replace the Ease of Access application (Utilman.exe) with cmd.exe, and this can be done from a boot media. Afterwards you can click the Ease of Access button to access Command Prompt, and reset local administrator password with cmd.


1 Answers

Try the DirectoryEntry class instead of ManagementObject class.

like image 178
Ely Avatar answered Sep 28 '22 18:09

Ely