Create AD user with C#

Asked

Viewed 1,359 times

7

Does anyone have a code for creating user in the C# net ad? I’m new to C# development and I tried through the codes I saw here and I couldn’t

  • The question is good (+1). Just a hint, you could include the code you already tried and didn’t work. So people who are going through the same problem with similar code can benefit even more from the issue.

1 answer

5

You can do it with class UserPrincipal. 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 over which operations (such as user creation) are executed.

This class has a builder that you pass the call ContextType which may have the following values:

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

That one ContextType represents the storage the main part of. In case of creating a user in AD you would pass ContextType.Domain.

Then you just have to create an instance of UserPrincipal 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:

  • how to get the Login and title from the Userprincipal?

  • @Jhonatan, it is possible yes, there is a way to access some properties, I think it works for these. Don’t you want to post this as a new question? Then I’ll find a way there and it’ll be easier to find for those who need it later.

  • Thank you! question posted on: [link] http://answall.com/questions/23252/obten-organization-departament-e-organization-title-com-userprincipal-ad-e-c

Browser other questions tagged

You are not signed in. Login or sign up in order to post.