c# LDAP create new active directory user

public static string CreateUserAccount(string ldapPath, string userName, string userPassword)
    string oGUID = string.Empty;
        //    for example an ldap path : 
        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;
        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;


    catch (System.DirectoryServices.DirectoryServicesCOMException E)
        //DoSomethingwith --> E.Message.ToString();

    return oGUID;

About bpostaci
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 )

Connecting to %s

%d bloggers like this: