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;
}
Advertisement