PasswordEntry to change password: different behavior between Vista / Server2008

On a Vista dev machine, I successfully used this code to change the password for the Administrator user:

directoryEntry.Invoke("SetPassword", "new"); 

When I moved it to my Dev 2008 machine, this code did not work, and I was forced to use the following code:

 directoryEntry.Invoke("ChangePassword", new object[] { "old", "new" }); 

My question is why?

In both cases, I created a DirectoryEntry object as such:

 DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username)); 

Thanks! 8)

In case you guys find this useful, this is real code.

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.DirectoryServices; using System.Security.Principal; namespace AccountMod { class Program { static void Main() { Console.WriteLine("Attempting reset...\n"); try { String machineNameAndUser = WindowsIdentity.GetCurrent().Name.ToString(); String machineName = WindowsIdentity.GetCurrent().Name.ToString().Substring(0, machineNameAndUser.IndexOf('\\')); Console.WriteLine("Computer name: " + machineName); ResetPassword(machineName, "Administrator", "new"); //ChangePassword("Administrator", "current", "new"); Console.WriteLine("Finished..."); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine(e.InnerException); } Console.ReadKey(); } 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); //directoryEntry.Invoke("ChangePassword", new object[] { "current", "new" }); } } } 
+6
c # change-password active-directory directoryservices
source share
2 answers

You (or can you upgrade to) .NET 3.5? AD integration for users, groups, computers has been greatly improved in .NET 3.5 - see the MSDN article Guide for Security Managers in the .NET Framework 3.5 for details.

In your case, you can do something like:

 // establish context for local machine PrincipalContext ctx = new PrincipalContext(ContextType.Machine); // find the "Administrator" account UserPrincipal admin = UserPrincipal.FindByIdentity(ctx, "Administrator"); // set the password to a new value admin.SetPassword("new-top-secret-password"); admin.Save(); 

and you're done! WinNT: provider WinNT: very limited in what it can do, and should be avoided if possible.

+5
source share

Check the user properties for which you want to set a password if

user cannot change password

it is checked and then sets the password using directoryEntry.Invoke("SetPassword", "new"); Use administrator credentials when creating the DirectoryEntry object or clear the "user cannot change password" check box.

0
source share

All Articles