Active Directory用户组成员身份GroupPrincipal

时间:2011-03-09 14:33:06

标签: c# active-directory

我正在尝试使用GroupPrincipalSystem.DirectoryServices.AccountManagement命名空间的一部分)来填充类型字符串列表,因此我可以检查用户是否是Active Directory组的成员。这是我到目前为止编写的编辑类:

public class ActiveDirectoryMembership
{
    private PrincipalContext context = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);
    private List<string> GroupName {get;set;}

    public ActiveDirectoryMembership() 
    {
         //Code snipped - this part returns a list of users
         populateGroups();
    }

    private void populateGroups()
    {
        GroupPrincipal SearchGroup = GroupPrincipal.FindByIdentity(context, "Group Name");
        GroupName = new List<string>();
        foreach (UserPrincipal p in GroupName.GetMembers())
        {
           GroupName.add(p.SamAccountName);
        }
    }

那么,我哪里错了?

提前致谢:)

2 个答案:

答案 0 :(得分:4)

您的代码修改工作(我做了测试以确保):

    private static readonly string DomainName = "domaincontrollercomputer.domain.com";
    private static readonly string DomainContainer = "DC=DOMAIN,DC=COM";
    private static readonly string ADGroupName = "AD Group Name";
    private List<string> GroupName {get;set;}

    private void populateGroups()
    {
        using (var ctx = new PrincipalContext(ContextType.Domain, DomainName, DomainContainer))
        {
            using (var grp = GroupPrincipal.FindByIdentity(ctx, ADGroupName))
            {
                GroupName = new List<string>();
                foreach (var member in grp.GetMembers())
                {
                    GroupName.Add(member.SamAccountName);
                }
            }
        }
    }

答案 1 :(得分:0)

我认为你的方法中有一个简单的拼写错误 - 你将组主体变为SearchGroup(检查 NULL ,顺便说一下!!)然后你抓住了成员关GroupName ??

试试这个:

private void populateGroups()
{
    GroupPrincipal SearchGroup = GroupPrincipal.FindByIdentity(context, "Group Name");

    if(SearchGroup != null)
    {
       GroupName = new List<string>();

       // call 'GetMembers' on 'SearchGroup' here!! 
       foreach (UserPrincipal p in SearchGroup.GetMembers())  
       {
          GroupName.add(p.SamAccountName);
       }
    }
}