Adding Active Directory Users via C#–Automated

Recently I needed to add a bunch of users (5000) to Active Directory and I needed to do this in an automated way. I did some research and found this Assembly from Microsoft ‘System.DirectoryServices.AccountManagement.dll’.

You can read more about it here: Account Management Library

What I needed is, I had a list of users in the database which than I needed to add to Active Directory so in the application I will be getting the users from context, iterate through them and add them one by one into Active Directory by using the AccountManagement Library provided by Microsoft

Lets dive into the code that does this automated inserting of Users into Active Directory.

When creating the project we need to add the required references for this Library/Utility

This is a list of constants that I need for the code, you can find the default password which will be stored for every user (its a default than I set the password to expire so that users will have to change it at their first login) the others consts are self explainable.

Than I have the context which contains the Users (A database with users) – its a mock context I did not use the real one here. IGNORE the dispose function

I also needed to create a method to check if the user was already added before, so that I update his/her name if it already exists in Active Directory. This is very handy if you need to update your active directory users accordingly (sync them up with the database).

This is the code, with iteration that adds the users to AD

  • SAM Account Name is the Username that is used to login
  • ExpirePasswordNow method ensures that the default password which was set will have to changed at first user’s login attempt.
  • Name is the Full Name of the User
  • EmailAddress is the Email of the Users NOTE, if the email can be empty you need to make a check else it will throw an error because the email cannot be set as empty. its either NULL or a valid Email address
  • Save function persists the user to AD

Thats all folks!

Leave a Reply

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