Friday, March 27, 2009

Creating Active Directory accounts with C#

My preferred method for Active Directory administration with .NET is to use the Directory Services API. First off, add a reference to the System.DirectoryServices dll in your project, then add the following to the top of your class to reference that API.

using System.DirectoryServices;

1. Create the Directory Entry object for the user:

DirectoryEntry deUser = new DirectoryEntry();

2. create the object for the parent container for the user:

objUsersContainer = new DirectoryEntry(@"LDAP://ou=Users,dc=mydomain,dc=com");

NOTE: You must be authenticated at this point with an account that has permissions to create Active Directory users on your domain. If you wish to explicitly pass credentials to this object, you can use the following:

objUsersContainer = new DirectoryEntry(@"LDAP://ou=Users,dc=mydomain,dc=com", "userid", "password", AuthenticationTypes.Secure);

3. Bind the user object to its parent container:

deEntry = objUsersContainer.Children.Add("cn=User Test", "user");

NOTES:
1st Parameter:
"cn=User Test". This cn value must be unique to this container, so use some kind of method for finding a unique cn. This can be done with the Directory Searcher. Google this or wait until I add to another post: ) Or comment to this post...i'll help out.

2nd Parameter: "user". This specifies what type of object your child is.

4. Set the required properties:

deEntry.Properties["samaccountname"].Value = "newuserid"; //This is the user's login id
deEntry.Properties["displayname"].Value = "User, Test"; //This is the text that will display in a global address list

5. Save you're changes!:

deEntry.CommitChanges();

There it is! The account should exist in your domain. However, this is most likely not all that need's to be done. The user still needs a password and be enabled to be able to log in and you may wish to set other properties on this account. My next post will cover these methods.

No comments: