0

In Sharepoint (or any ASP.NET web application) I want to have a function to create AD users. I'm using System.DirectoryServices.AccountManagement for this task, but I'm getting into trouble. Here is my code:

using (var pc = new PrincipalContext(ContextType.Domain,"DOMAIN","administrator","password"))
{
    if (pc.ValidateCredentials("administrator", "password"))
    {
        UserPrincipal up = new UserPrincipal(pc, username, password, true);
        up.Save();
    }
}

The user gets created but it is disabled. I know that my administrator:password pair is correct because "if" statement is returning true. Also during creation I receive Exception:

Exception has been thrown by the target of an invocation.

I checked PrincipalContext object and it is connecting to domain controller with "administrator" account. What could be the reason of this error and up.Save() function throwing Exception ?

pirmas naujas
  • 180
  • 1
  • 1
  • 13

1 Answers1

0

Can you try the following:

using (var pc = new PrincipalContext(ContextType.Domain,"DOMAIN","administrator","password"))
            {
                using (var up = new UserPrincipal(pc))
                {
                    up.SamAccountName = textboxUsername.Text; // Username
                    up.SetPassword(textboxPassword.Text); // Password
                    up.Enabled = true;
                    up.ExpirePasswordNow();
                    up.Save();
                }
            }

This should at least make sure that the user is created and is enabled. Let me know if it works.

lem.mallari
  • 1,274
  • 12
  • 25