c# LDAP create new active directory user


public static string CreateUserAccount(string ldapPath, string userName, string userPassword)
{
    string oGUID = string.Empty;
    try
    {
        //    for example an ldap path : 
        //    10.20.12.11:389/OU=PORTAL,DC=TESTDOMAIN,DC=entptst,DC=local
        string connectionPrefix = "LDAP://" + ldapPath;
        DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix, "TESTDOMAIN\\admin", "secret");
        DirectoryEntry newUser = dirEntry.Children.Add("CN=" + userName, "user");
        newUser.Properties["samAccountName"].Value = userName;
        newUser.CommitChanges();
        oGUID = newUser.Guid.ToString();

        //If you dont have an SSL connection you can not set password
        newUser.Invoke("SetPassword", new object[] { userPassword });
        newUser.Properties["LockOutTime"].Value = 0;

        //Enable user
        int val = (int)newUser.Properties["userAccountControl"].Value;
        newUser.Properties["userAccountControl"].Value = val & ~0x2;

        newUser.CommitChanges();


        dirEntry.Close();
        newUser.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //DoSomethingwith --> E.Message.ToString();

    }
    return oGUID;
}
Advertisements

About bpostaci
Sr. Support Escalation Engineer in Microsoft.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: