How to update data in Active Directory using DirectoryEntry?

0

I want to update user expire date in Active Directory. If already have user then update expire date. I try to call CommitChanges with this code:

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

When I run it show error like this.

at System.DirectoryServices.DirectoryEntry.CommitChanges()
at NIDCardCS.Form1.AddToAD(String fNm, String lNm, String uNm, String) in C:\Users\Test\Form1.cs:line 289
Exception thrown: 'System.DirectoryServices.DirectoryServicesCOMException' in System.DirectoryServices.dll
System.DirectoryServices.DirectoryServicesCOMException (0x80071392): The object already exists.

How to update data in Active Directory using DirectoryEntry ?

c#
active-directory
directoryentry
asked on Stack Overflow Mar 25, 2019 by user572575 • edited Mar 25, 2019 by marc_s

1 Answer

1

If you don't know the path to the user, use DirectorySearcher to find the user. If you do know the path, construct a new instance using. e.g.,

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

You don't normally need to Clear a value before setting it.

Always use using if you can as it reduces the change of you forgetting to call Close.

answered on Stack Overflow Jun 3, 2019 by user2871239

User contributions licensed under CC BY-SA 3.0