0

using (var ctx = new PrincipalContext(ContextType.Domain, _domain, _user, _password))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx,IdentityType.SamAccountName, sAMAccountName))
    {
        PrincipalSearchResult<Principal> userGroups = user.GetGroups();                    
        using (userGroups)
        {
            foreach (Principal p in userGroups)
            {
                using (p)
                {
                    result.Add(p.Guid == null ? Guid.Empty : (Guid)p.Guid);
                }
            }
        }
    }
}

|

    1

    0

    public static IEnumerable<Guid> GetUserMemberOf(DirectoryEntry de) {
        var groups = new List<Guid>();
    
        //retrieve only the memberOf attribute from the user
        de.RefreshCache(new[] {"memberOf"});
    
        while (true) {
            var memberOf = de.Properties["memberOf"];
            foreach (string group in memberOf) {
                using (var groupDe = new DirectoryEntry($"LDAP://{group.Replace("/", "/")}") {
                    groupDe.RefreshCache(new[] {"objectGUID"});
                    groups.Add(new Guid((byte[]) groupDe.Properties["objectGUID"].Value));
                }
            }
    
            //AD only gives us 1000 or 1500 at a time (depending on the server version)
            //so if we've hit that, go see if there are more
            if (memberOf.Count != 1500 && memberOf.Count != 1000) break;
    
            try {
                de.RefreshCache(new[] {$"memberOf;range={groups.Count}-*"});
            } catch (COMException e) {
                if (e.ErrorCode == unchecked((int) 0x80072020)) break; //no more results
    
                throw;
            }
        }
        return groups;
    }
    

    new DirectoryEntry($"LDAP://{distinguishedName}")

    var ds = new DirectorySearcher(
                    new DirectoryEntry($"LDAP://{_domain}"),
                    $"(&(objectClass=user)(sAMAccountName={sAMAccountName}))");
    ds.PropertiesToLoad.Add("distinguishedName"); //add at least one attribute so it doesn't return everything
    
    var result = ds.FindOne();
    var userDe = result.GetDirectoryEntry();
    

    |
    • 1