【问题标题】:How to update data in Active Directory using DirectoryEntry?如何使用 DirectoryEntry 更新 Active Directory 中的数据?
【发布时间】:2019-03-25 05:05:37
【问题描述】:

我想更新 Active Directory 中的用户过期日期。如果已经有用户,则更新过期日期。我尝试使用此代码致电CommitChanges

if (result == null)
{
    DirectoryEntry newUser = dirEntry.Children.Add("CN=" + fNm, "user");
    newUser.Properties["sAMAccountName"].Value = uNm;
    newUser.Properties["givenName"].Value = fNm;
    newUser.Properties["sn"].Value = lNm;
    newUser.Properties["displayName"].Value = NID_Number;

    dateEng = DateTime.Today.AddDays(3); ;

    newUser.Properties["accountExpires"].Value = dateEng.ToFileTime().ToString();

    newUser.Properties["userPrincipalName"].Add(uNm + "@pkru.ac.th");
    newUser.CommitChanges();
    oGUID = newUser.Guid.ToString();

    const int UF_NORMAL_ACCOUNT = 0x0200;
    const int UF_DONT_EXPIRE_PASSWD = 0x10000;
    newUser.Properties["userAccountControl"].Value = UF_NORMAL_ACCOUNT + UF_DONT_EXPIRE_PASSWD;
    newUser.Invoke("SetPassword", new object[] { NID_Number });

    newUser.CommitChanges();

    dirEntry.Close();
    newUser.Close();
}
else
{
    gp = SearchUserGroup(result);

    if (string.Equals(gp, "ABC"))
    {
        dateEng = DateTime.Today.AddDays(7); ;
        DirectoryEntry newUser = dirEntry.Children.Add("CN=" + fNm, "user");
        newUser.Properties["accountExpires"].Clear();
        newUser.Properties["accountExpires"].Value = dateEng.ToFileTime().ToString();
        newUser.CommitChanges();
    }
}

当我运行它时会显示这样的错误。

在 System.DirectoryServices.DirectoryEntry.CommitChanges()
在 NIDCardCS.Form1.AddToAD(String fNm, String lNm, String unNm, String) 在 C:\Users\Test\Form1.cs:line 289
抛出异常:System.DirectoryServices.dll 中的“System.DirectoryServices.DirectoryServicesCOMException”
System.DirectoryServices.DirectoryServicesCOMException (0x80071392): 对象已经存在。

如何使用DirectoryEntry 更新 Active Directory 中的数据?

【问题讨论】:

  • 您真的阅读错误信息了吗? 对象已经存在有什么不清楚的地方。 .....
  • 我应该删除对象并重新创建用户吗?

标签: c# active-directory directoryentry


【解决方案1】:

如果您不知道用户的路径,请使用DirectorySearcher 查找用户。如果您确实知道路径,请使用构造一个新实例。例如,

using (var entry = new DirectoryEntry("LDAP://CN=first last,OU=blah,DC=blah"))
{
    entry.Properties["accountExpires"].Value = blah
    entry.CommitChanges()
}

您通常不需要在设置值之前Clear

如果可以,请始终使用using,因为它可以减少您忘记致电Close的变化。

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多