How to add new user using DirectoryServices
In our previous article, How to get full name of logged in user,
we showed how you can get full name of a user in a given domain or machine. You
can extend that idea to obtain any information you want for a given user. This
artcile will describe how you can add a new user account into your domain or
machine using .Net DirectoryServices classes. We will be using WinNT provider
for illustrations in this article. But you can extend the examples to use LDAP
or AD providers.
Here are the key steps that you will need to perform to create new account.
Create a new
DirectoryEntry object and specify the machine name as
User accounts are created as nodes corrresponding to User schema class
in Active Directory. Therefore we will add a new
Children collection of the machine. The key thing to rememeber
will be that when you add new entry, make sure that the schema class name is User.
When you add a new node in
Children collection, it will return you
the newly created object. At this stage the information has not been added to
your machine or active directory tree.
Now you can set all the values that you need to set for a given account.
Following is the list of property names that you can set for the account.
For more information on these properties please read Active Directory Services
Interface(ADSI) section in Microsoft
You must have noticed from the above list that there is no property to set or
get user password value. Operating system does not give access to clear text
password value. So we can't expect and property or method to get it. In ADSI,
IAdsUser interface provides
SetPassword method to set a
user's password. This is where
Invoke method of
class comes handy. So we call
Invoke to set the password value.
Invoke method can be used to call native methods on underlying
active directory objects. There is one important thing to remeber when you set
a user's password value. If you are using LDAP provider, then the user
account should already have been created in the system by calling
SetInfo method. But WinNT provider does not have this
restriction. You can set password value without commiting the changes first.
The last step would be to actually create the account in the machine or domain.
This is done by calling
CommitChanges method on newly added
The following code demonstrates all the steps that we described above.
private void AddUser(string strDoamin, string strLogin, string strPwd)
DirectoryEntry obDirEntry = null;
obDirEntry = new DirectoryEntry("WinNT://" + strDoamin);
DirectoryEntries entries = obDirEntry.Children;
DirectoryEntry obUser = entries.Add(strLogin, "User");
object obRet = obUser.Invoke("SetPassword", strPwd);
catch (Exception ex)
Please feel free to send your suggestions directly to us at