Today I’ll give You a hint on how to add a new user to an Active Directory. It’s not a big deal to do that, but I have to admit, that I had a little problem with SetPassword function. When I tried to set password for the user I’ve created, it threw me some errors like “Access denied” or “Unexpected error occurred”, although I worked in the context of the domain admin. I googled about it and I’ve found many answers, but any of them worked for me. After some brainstorm(:)) I managed to get a very simple workaround.

I hope that this code will be useful for some of You. The namespace which You have to add to use below code is System.DirectoryServices.AccountManagement

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "zavaz", "OU=Test,DC=zavaz,DC=pl", ContextOptions.SimpleBind, AdminLogin, AdminPassword))
{
   using (UserPrincipal up = new UserPrincipal(pc))
   {
      up.Name = "John Test";
      up.DisplayName = "John Test";
      up.SamAccountName = "j.test";
      up.UserPrincipalName = "j.test@zavaz.pl";
      up.Enabled = true;
      up.PasswordNeverExpires = true;
      up.UserCannotChangePassword = false;
      //up.SetPassword("newPassword"); - didn't work for me here
      up.Save();

      try
      {
           up.ChangePassword("", "newPassword"); //works great
      }
      catch (Exception ex)
      {
           up.Delete();
           throw new Exception(ex.Message, ex);
      }
   }
}