使用C#创建新的Active Directory时无法设置密码

时间:2014-06-20 08:09:54

标签: c# active-directory

我很难用C#创建Active Directory用户

这是我用来创建新用户的代码:

public bool CreateUser(string userName, string password)
        {
            try
            {
                DirectoryEntry entry = new DirectoryEntry(lDAPConnectionString, aDConnectionUserName, aDConnectionPassword, AuthenticationTypes.Secure);

                // Use the Add method to add a user to an organizational unit.
                DirectoryEntry user = entry.Children.Add("CN=" + userName, "user");
                // Set the samAccountName, then commit changes to the directory.
                user.Properties["samAccountName"].Value = userName;
                user.Properties["userPrincipalName"].Value = userName + Constants.ADProperties.ADUPNLogonSuffix;

                user.CommitChanges();

                // Set password never expire
                int NON_EXPIRE_FLAG = 0x10000;
                int val = (int)user.Properties["userAccountControl"].Value;
                user.Properties["userAccountControl"].Value = val | NON_EXPIRE_FLAG;
                user.CommitChanges();

                // Enable User
                val = (int)user.Properties["userAccountControl"].Value;
                user.Properties["userAccountControl"].Value = val & ~(int)Constants.ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE;
                user.CommitChanges();
                user.RefreshCache();

                // Set password
                user.UsePropertyCache = true;
                user.Invoke("SetOption", new object[] { Constants.ADS_USER_FLAG_ENUM.ADS_OPTION_PASSWORD_PORTNUMBER, Constants.ADProperties.ADPort });
                user.Invoke("SetOption", new object[] { Constants.ADS_USER_FLAG_ENUM.ADS_OPTION_PASSWORD_METHOD, Constants.ADS_USER_FLAG_ENUM.ADS_PASSWORD_ENCODE_CLEAR });
                user.Properties["LockOutTime"].Value = 0; 
                user.Invoke("SetPassword", new object[] { password });

                user.CommitChanges();

                return true;
            }
            catch (Exception)
            { 
            }

            return false;
        }      

当我使用它时,它会抛出异常:“服务器不愿意处理请求。(HRESULT异常:0x80072035)” at line:“user.Invoke(”SetPassword“,new object [] {password});”

我尝试了很多方法,但我无法解决这个问题。 任何帮助都会被批评。 感谢

1 个答案:

答案 0 :(得分:0)

错误0x80072035通常由于密码策略而返回。这可以是长度,特殊字符,密码历史(之前使用过的密码)。处理这些错误有助于向用户提供反馈。可以在此处找到处理这些错误的指南:

http://www.ozkary.com/2015/03/active-directory-setpassword-or.html