将用户添加到Active Directory时,C#Access被拒绝

时间:2015-06-22 05:41:36

标签: c# active-directory

string strName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // "MW\\dalem"
        string domainName = strName.Split('\\')[0];
        using(var pc = new PrincipalContext(ContextType.Domain, domainName))
            {
                using (var user = new UserPrincipal(pc, Admin-Username, Admin-Pass, true))
                {
                    fullname = fname + " " + lname;
                    user.SamAccountName = username;
                    user.SetPassword(password);
                    user.GivenName = fname;
                    user.Surname = lname;
                    user.DisplayName = fullname;
                    user.Save();
                }
            }

我试图将用户添加到活动目录,我收到错误

  

"拒绝访问"

user.Save();行。我不明白为什么,因为我有完整的管理员权限。这是我尝试将用户添加到活动目录的第三种或第五种方法。

1 个答案:

答案 0 :(得分:0)

您可以通过保存数据库上下文来实现此目的:

string strName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // "MW\\dalem"
        string domainName = strName.Split('\\')[0];
        using(var pc = new PrincipalContext(ContextType.Domain, domainName))
            {
                using (var user = new UserPrincipal(pc, Admin-Username, Admin-Pass, true))
                {
                    fullname = fname + " " + lname;
                    user.SamAccountName = username;
                    user.SetPassword(password);
                    user.GivenName = fname;
                    user.Surname = lname;
                    user.DisplayName = fullname;
                    userPrincipal.Add(user);
                }
            pc.SaveChanges();
            }