This code will create a local account with the password never expires option set:
using System.DirectoryServices;
DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost");
DirectoryEntries entries = hostMachineDirectory.Children;
bool userExists = false;
foreach (DirectoryEntry each in entries)
{
userExists = each.Name.Equals("NewUser",
StringComparison.CurrentCultureIgnoreCase);
if (systemtestUserExists)
break;
}
if (false == userExists)
{
DirectoryEntry obUser = entries.Add("NewUser", "User");
obUser.Properties["FullName"].Add("Local user");
obUser.Invoke("SetPassword", "abcdefg12345@");
obUser.Invoke("Put", new object[] {"UserFlags", 0x10000});
obUser.CommitChanges();
}
The 0x10000 flag means PasswordNeverExpires.
I spent a long time figuring out how to create a local user account with the password set not to expire. It seems that when you try to use:
int val = (int)newUser.Properties["userAccountControl"].Value;
newUser.Properties["userAccountControl"].Value = val | 0x10000
permissions from active directory come into play. If you have active directory permissions everything works fine. If you don’t then getting the userAccountControl property will always result in a null value. Trying to set userAccountControl will result in an exception “The directory property cannot be found in the cache”.
However after much hunting around I found another property “UserFlags” that needs to be set using Invoke. You can use this to set the flag on a local account. I’ve tried this code and it worked on windows server 2008.
Hope this helps