Reputation: 105
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 ?
Upvotes: 5
Views: 11124
Reputation: 1484
*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
Upvotes: 5
Reputation: 1391
This is my code to resolve this issue:
// Add new user to OU
var username = "testuser_01";
var userDn = "LDAP://yourdomain.local:389/OU=testou,cn=yourdomain,cn=local";
var ouUserEntry = new DirectoryEntry(userDn, "yourAdminUser", "yourAdminPassword", AuthenticationTypes.Secure);
var newUserEntry = ouUserEntry.Children.Add("CN="+ username, "user");
newUserEntry.Properties["sAMAccountName"].Value = username;
newUserEntry.Properties["userPrincipalName"].Value = username + "@abc.com";
newUserEntry.Properties["displayName"].Value = username;
// Commit before enable account
newUserEntry.CommitChanges();
// Set password
newUserEntry.Invoke("SetPassword", "yourUserPassword");
// Enable Account & Password never expired (NORMAL_ACCOUNT | DONT_EXPIRE_PASSWORD)
newUserEntry.Properties["userAccountControl"].Value = 66080; // integer value in image above
newUserEntry.CommitChanges();
Upvotes: 0
Reputation: 755227
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
Basically, you can define a machine context and easily create new users on your 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 really easy to play around with users and groups in AD!
Upvotes: 8