4

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 ?

4

3 回答 3

7

如果您使用的是 .NET 3.5 及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM) 命名空间。在这里阅读所有相关信息:

基本上,您可以定义机器上下文并轻松地在本地服务器上创建新用户:

// 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();
}

新的 S.DS.AM 使得在 AD 中与用户和组一起玩变得非常容易!

于 2012-06-14T05:11:39.080 回答
5

*已编辑

对于域帐户:

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

对于本地帐户:

我相信您会使用“UserFlags”而不是 userAccountControl。此外,您还必须使用 ADS_UF_DONT_EXPIRE_PASSWD 标志而不是Microsoft 文章中所述的 NON_EXPIRE_FLAG

于 2012-06-14T04:39:50.777 回答
0

这是我解决此问题的代码:
在此处输入图像描述

// 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();
于 2018-06-27T12:00:28.803 回答