1

基本上,我找到了一个帖子,可以解决我们在应用程序中遇到的问题,解决方案是:

    private static void listGroupMembers(string groupDistinguishedName, PrincipalContext ctx, List<UserPrincipal> users)
{
    DirectoryEntry group = new DirectoryEntry("LDAP://" + groupDistinguishedName);
    foreach (string dn in group.Properties["member"])
    {

        DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + dn);
        System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;

        object[] objCls = (userProps["objectClass"].Value) as object[];

        if (objCls.Contains("group"))
            listGroupMembers(userProps["distinguishedName"].Value as string, ctx, users);

        if (!objCls.Contains("foreignSecurityPrincipal"))
        {                    
            UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, dn);
            if(u!=null)  // u==null for any other types except users
                users.Add(u);
        }
    }                 
}

但是我正在尝试搜索本地组,所以如果我将目录条目更改为:

DirectoryEntry groupEntry =
            new DirectoryEntry(string.Format("WinNT://{0}/{1},group", Environment.MachineName, groupName));

然后它不起作用,它说该属性不存在。除了本地组和用户,我该如何执行上述操作?

4

1 回答 1

0

基本上为了解决这个问题,我最终做了:

protected bool IsUserInLocalGroup(string userName, string group)
    {
        using (DirectoryEntry computerEntry = new DirectoryEntry("WinNT://{0},computer".FormatWith(Environment.MachineName)))
        using(DirectoryEntry groupEntry = computerEntry.Children.Find(group, "Group"))
        {
            foreach (object o in (IEnumerable)groupEntry.Invoke("Members"))
            {
                using (DirectoryEntry entry = new DirectoryEntry(o))
                {
                    if (entry.SchemaClassName.Equals("User", StringComparison.OrdinalIgnoreCase) && entry.Name.Equals(userName, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }
于 2013-03-25T14:10:30.383 回答