将现有用户添加到现有组时出现C#错误

时间:2018-09-18 18:34:01

标签: c# directoryservices

我有两个站点,每个站点都有自己的Scheduler,具有足够的权限来执行其工作。我们创建了一个应用程序,使他们可以将用户需要的所有内容快速添加到AD中。问题在于,有时学生会暂时从一个站点转移到另一个站点。在新站点上时,他们将需要访问所有原始内容,以及对新站点内容的访问权限。

我有一个请求,要求添加一个按钮,该按钮将允许他们快速添加其他网站用户组,而不删除原始网站用户组。

我得到的错误是:

Error adding User to Group.
System.Directory.Services.AccountManagement.NoMatchingPrincipalException:
No principal matching the specified paramenters was found
    at 
System.DirectoryServices.AccountManagement.principalCollection.add(principalContext context, identitytype itedentity type, string identitiyvalue)
at AddStudentUser.Form2.AddUserToGroup_fm2(string userID, string groupName, string siteName) identitiyvalue
c:\projects\AddStudentUser\AddStudentUser\Form2.cs:line 113

这是我正在调用的代码:

    private void btnUpdateExit_Click(object sender, EventArgs e)
    {
        //userUPN will equal Loginname@domain.com
        string userUPN = this.tbUserLoginName.Text.Trim().ToString() + Form1.Globs.strUPN;
        if (this.cbSite1.Checked == true & this.cbSite1.Enabled==true)
        {
            AddUserToGroup_fm2(userUPN, "Site1", Form1.Globs.strSUUADC);
            AddUserToGroup_fm2(userUPN, "Crew_Site1", Form1.Globs.strSite1ADC);
            AddUserToGroup_fm2(userUPN, "WWW-Site1", Form1.Globs.strSite1ADC);
            MessageBox.Show("User has been added to the Site1 Groups.");
        }
        if (this.cbSite2.Checked == true & this.cbSite2.Enabled == true)
        {
            AddUserToGroup_fm2(userUPN, "Site2", Form1.Globs.strWRIADC);
            AddUserToGroup_fm2(userUPN, "Crew_Site2", Form1.Globs.strSite2ADC);
            AddUserToGroup_fm2(userUPN, "WWW-Site2", Form1.Globs.strSite2ADC);
            MessageBox.Show("User has been added to the Site2 Groups.");
        }
        this.Close();
    }
    public void AddUserToGroup_fm2(string userId, string groupName, string siteName)
    {
        try
        {
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, siteName))
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
                group.Members.Add(pc, IdentityType.UserPrincipalName, userId);

                group.Save();
            }
        }
        catch (Exception E)
        {
            MessageBox.Show("Error adding User to Group. " + E);

        }
    } 

奇怪的是,如果我添加一个新用户,则在不同表单上的相同代码可以正常工作。我最初尝试调用该代码,但是遇到了与现在相同的错误。我想分离代码,以便可以在不影响原始功能的情况下对其进行更改,因为在将新用户添加到现有组时,它可以正常工作。

感谢您的协助。

1 个答案:

答案 0 :(得分:0)

IdentityType.SamAccountName

        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, siteName))
        {
            GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
            group.Members.Add(pc, IdentityType.SamAccountName, userId);

            group.Save();
        }
相关问题