Search code examples
c#directoryentry

Set 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 what i want to do is to create a windows user and set the password never expired , But i do not know how to do this ?


Solution

  • *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 you'd use "UserFlags" instead of userAccountControl. Also you would have to use ADS_UF_DONT_EXPIRE_PASSWD flag instead of NON_EXPIRE_FLAG as described in an article by Microsoft