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

时间:2019-03-25 05:05:37

标签: c# active-directory directoryentry

我想更新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 uNm,String)在C:\ Users \ Test \ Form1.cs:line 289
  抛出异常:System.DirectoryServices.dll中的'System.DirectoryServices.DirectoryServicesCOMException'
  System.DirectoryServices.DirectoryServicesCOMException(0x80071392):该对象已存在。

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

1 个答案:

答案 0 :(得分:0)

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

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

通常不需要在设置之前Clear一个值。

如果可以的话,请始终使用using,因为这样可以减少您忘记拨打Close的麻烦。

相关问题