3

I'm working in C# pulling active directory groups for users. For some reason the app is throwing an error for one user on the following code snippet

PrincipalSearchResult<Principal> groups = user.GetGroups();
int total = groups.Count();

Error:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

I have never seen a Count() method throw this kind of error before.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Finuve
  • 73
  • 7
  • can you show how you Instantiating the Principal Object.. I think that may be one of the reasons it's failing. for example in order to get groups you need to get the users first one would think like so `UserPrincipal user = new UserPrincipal(...);` here is something that you can look at to get better example of how to do it http://stackoverflow.com/questions/5309988/how-to-get-the-groups-of-a-user-in-active-directory-c-asp-net – MethodMan Apr 02 '13 at 15:36
  • Did you check that the `groups` results isn't `NULL` ?? – marc_s Apr 02 '13 at 15:38
  • 1
    @marc_s That was my first thought, but then you'd expect to see a `NullReferenceException` instead of an `IndexOutOfRangeException`, no...? – rsbarro Apr 02 '13 at 15:39
  • @rsbarro: you're probably right on that one! :-) – marc_s Apr 02 '13 at 15:39
  • Similar problem mentioned in the second answer here: http://stackoverflow.com/questions/11846097/active-directories-userprincipal-current-getgroups-returns-group-on-local-not – rsbarro Apr 02 '13 at 15:44
  • PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain, ADDomain, ADDomain + "\\" + ADUser, ADPassword); UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, ntID); – Finuve Apr 02 '13 at 16:19
  • kerberos isn't much of an option... – Finuve Apr 02 '13 at 16:19
  • I discovered groups in an unknown state which caused this error. Very weird - but if the user had such groups in their MemberOf attribute, a foreach or converting ToList would throw an exception – PBMe_HikeIt Apr 19 '22 at 18:46

0 Answers0