Create user in AD with C #

7

Does anyone have a code for user creation in ad in C # .NET? I am developing in C # beginner and tried through the codes I saw here and could not do it.

    
asked by anonymous 02.07.2014 / 16:58

1 answer

5

You can do this with the UserPrincipal class. It represents a user of your domain. When you build it you can pass an instance of PrincipalContext . This last class encapsulates the server or domain against which operations (such as user creation) are performed.

This class has a constructor that passes the named ContextType which can have the following values:

  • ContextType.ApplicationDirectory
  • ContextType.Domain
  • ContextType.Machine

This ContextType represents the storage of which the principal is a part. In case of creating a user in AD you would pass ContextType.Domain .

Then you just have to create an instance of UserPrincipal by passing the PrincipalContext that you created, set the properties, and save. It looks like this:

using (var contextoPrincipal = new PrincipalContext(ContextType.Domain))
{
    using (var usuarioPrincipal = new UserPrincipal(contextoPrincipal))
    {
        usuarioPrincipal.SamAccountName = <Nome de Usuario Aqui>;
        usuarioPrincipal.EmailAddress = <Email Aqui>;
        usuarioPrincipal.SetPassword(<Senha Aqui>);
        usuarioPrincipal.Enabled = true; // Aqui você ativa essa conta, poderia não ativar, dependendo do caso de uso
        usuarioPrincipal.ExpirePasswordNow();
        usuarioPrincipal.Save();
    }
}

References:

02.07.2014 / 17:14