Set a Windows / AD password so that it never expires?

Here is my code:

using (DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer")) { DirectoryEntry NewUser = AD.Children.Add(username, "user"); string password = username + "123"; NewUser.Invoke("SetPassword", new object[] { password }); NewUser.CommitChanges(); NewUser.Close(); DirectoryEntry grp; grp = AD.Children.Find(groupname, "group"); if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); } } 

And I want to do this in order to create a Windows user and set a password that has never expired, But I do not know how to do this?

+4
source share
2 answers

* EDITED

For domain accounts:

 int NON_EXPIRE_FLAG = 0x10000; val = (int) NewUser.Properties["userAccountControl"].Value; NewUser.Properties["userAccountControl"].Value = val | NON_EXPIRE_FLAG; NewUser.CommitChanges(); 

For local accounts:

I believe that instead of UserAccountControl you should use "UserFlags"

+3
source

If you are using .NET 3.5 and above, you should check the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read more here:

Basically, you can define the context of the machine and easily create new users on the local server:

 // set up machine-level context using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine)) { // create new user UserPrincipal newUser = new UserPrincipal(ctx); // set some properties newUser.SamAccountName = "Sam"; newUser.DisplayName = "Sam Doe"; // define new user to be enabled and password never expires newUser.Enabled = true; newUser.PasswordNeverExpires = true; // save new user newUser.Save(); } 

The new S.DS.AM makes it very easy to play with users and groups in AD!

+5
source

All Articles