System.DirectoryServices.AccountManagement PrincipalContext模拟用于创建新用户

时间:2013-04-22 15:24:20

标签: asp.net sharepoint-2010 directoryservices userprincipal principalcontext

在Sharepoint(或任何ASP.NET Web应用程序)中,我想要一个创建AD用户的功能。我正在使用System.DirectoryServices.AccountManagement完成此任务,但我遇到了麻烦。这是我的代码:

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();
    }
}

用户已创建,但已被禁用。我知道我的管理员:密码对是正确的,因为“if”语句返回true。同样在创建过程中,我收到了例外:

Exception has been thrown by the target of an invocation.

我检查了PrincipalContext对象,并使用“administrator”帐户连接到域控制器。可能是这个错误和up.Save()函数抛出异常的原因是什么?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

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();
                }
            }

这至少应该确保创建并启用了用户。如果有效,请告诉我。