Maayan Cahani
Maayan Cahani

Reputation: 121

Adding new user to Active Directory

I searched for a long time for one full answer on how to create users in Active Directory using C# and I can't find any.

I would like to know the steps (including on where to specify AD credentials).

I don't mind if the user gets created using System.DirectoryServices or System.DirectoryServices.AccountManagement.

Here're the details. The DC is a remote computer (sitting in my lan). For example, the domain name is contoso-test.com.

Upvotes: 0

Views: 207

Answers (2)

smr5
smr5

Reputation: 2793

A little bit of google search and patience will do the trick.

Here's a sample code I've written a while back.

public static string CreateUser(string username, string password)
{
    //CREATE CONNECTION TO ACTIVE DIRECTORY
    using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "contosco-test.com"))
    {
        //CREATE A NEW USERPRINCIPAL OBJECT
        using (UserPrincipal principal = new UserPrincipal(ctx))
        {
            principal.Enabled = true; //IF NOT ENABLED YOU CAN'T AUTHENTICATE THE USER
            principal.UserPrincipalName = username;
            principal.Name = "name";
            principal.DisplayName = "firstname lastname";
            principal.EmailAddress = "[email protected]";
            principal.VoiceTelephoneNumber = "12345678910";
            principal.GivenName = "firstname";
            principal.Surname = "lastname";
            principal.SetPassword(password);
            try
            {
               principal.Save();
            }
            catch(Exception ex)           
            {
                throw;
            }
            //SEARCH FOR THE USER THAT JUST HAS BEEN CREATED
            using (var newUser = UserPrincipal.FindByIdentity(ctx, IdentityType.UserPrincipalName, username))
            {
                if (newUser != null)
                {
                   return newUser.Guid.ToString();
                }
            }
         }
    }
  return null;
}

I'm using System.DirectoryServices.AccountManagement namespace.

Upvotes: 1

shad0wec
shad0wec

Reputation: 375

public void AddToGroup(string userDn, string groupDn)
{
    try
    {
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
        dirEntry.Properties["member"].Add(userDn);
        dirEntry.CommitChanges();
        dirEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //doSomething with E.Message.ToString();
    }
}

Upvotes: 0

Related Questions