Setting a User’s `manager` Property in DirectoryServices

I was trying to run some code earlier today to set a user’s manager in ActiveDirectory using System.DirectoryServices, C#. I had code that did the following (actual code has a bunch of reusable methods for doing things like loading up UserPrincipal and DirectoryEntry objects, saving values, not hard coding key names etc – I am simplifying it here to get it all in one place):

using (var pc = new PrincipalContext(ContextType.Domain))
{
    // get the user's directory entry
    var up = UserPrincipal.FindByIdentity(pc, userName);
    var de = (DirectoryEntry)up.GetUnderlyingObject();
    
    // get manager directoryEntry
    var managerUp = UserPrincipal.FindByIdentify(pc, managerUserName);
    var managerDe = (DirectoryEntry)up.GetUnderlyingObject();
    
    // get the manager's distinguished name
    string managerDN = managerDe.Properties["distinguishedName"][0].ToString();

    // set the manager's distinguished name as the value for the `manager` property on the users DirectoryEntry and save
    de.Properties["manager"].Value = managerDN;
    de.CommitChanges();
}

However, when I ran this, I got a System.DirectoryServices.DirectoryServicesCOMException telling me:

A constraint violation occurred

Eventually, I was able to figure out the issue (leading to this post, which will hopefully help someone else out in the future): when setting the `manager` property of a DirectoryEntry, you should not set it to a string that includes the DistinguishedName of the manager. Rather, you want to retrieve the object returned by DirectoryServices for the
DistinguishedName of the manager, and set that object value directory. So the end of the code excerpt should look like this:

    object managerDN = managerDe.Properties["distinguishedName"][0];

    // set the manager's distinguished name as the value for the `manager` property on the users DirectoryEntry and save
    de.Properties["manager"].Value = managerDN;

Once I changed it to use the object value of the Distinguished name, I was able to CommitChanges to Active Directory successfully.