Question

Basically I found a post that has a solution for a problem we are having in our application and the solution was:

    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);
        }
    }                 
}

However I am trying to search a Local group so if I change the directory entry to say:

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

Then it doesn't work and it says that the property doesn't exist. How can I do the above but for a local group and user?

Était-ce utile?

La solution

Basically to fix this I ended up doing:

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;
        }
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top