How To Work With Active Directory (C#)

Active Directory is a little tricky when starting out. The recent project I worked on required me to add users (based on their NTAccounts) to a group. These users were not users of the machine, and therefore could not be found with UserPrincipal.FindByIdentity() for the machine you were adding the user on. What I knew about these users as that they had a Windows NTAccount and the domain they belonged to.

First I wanted to receive a datatables of NTAccount users from the active directory. I set up a Directory security class, which contains the directory’s group name and server I wanted to connect to. The below code shows how to query your active directory, retrieve the SID and traslate it to an NTAccounts


In order to add a users to the active directory which does not exist on the machine, you need to find the user on their domain. You can find the domain name from your user by going to your active directory and viewing the details of the user you are adding. If you have multiple domains you can split the NTAccount to get the domain abbreviation


In order to removing a users from the active directory works the same way as adding a user. Except call grp.Members.Remove(user) instead of grp.Members.Add(user). And there you go. You can now get/add/remove a user from your Active Directory in C#.

Leave a Comment

Your email address will not be published. Required fields are marked *