0

I have a c# application which uses Active Directory. I need to take all users which has at least a group starting with a specified value.

Here is my code:

using (PrincipalContext pcontext = new PrincipalContext(ContextType.Domain, "my-domain"))
{
    UserPrincipal uspPrincipal = new UserPrincipal(pcontext);

    // Here I think is the problem
    uspPrincipal.GetGroups().Any(x => x.Name.StartsWith("my value"));
    PrincipalSearcher ps = new PrincipalSearcher(uspPrincipal);
    var results = ps.FindAll();
    var resMembers = results.Where(x => x is UserPrincipal)
            .Cast<UserPrincipal>()
            .Distinct()
            .Select(x => x.GivenName + ", " + x.Surname).ToList();
} 

I receive a lot of users, but after I checked in Active Directory I found out that the number is bigger than expected result.

I know that I can bring firstly the groups that starts with seached value and then I can take for each group it's users but this means a lot of queries in Active Directory and I want to bring my users using just one interogation in Active Directory, so can I obtain neded users with a single search?

T-Heron
  • 5,385
  • 7
  • 26
  • 52
roroinpho21
  • 732
  • 1
  • 11
  • 27

2 Answers2

0

Any() returns a bool, so that won't actually give you the list of groups that you want.

This question addresses searching for groups that start with a certain value. The answer should help: Find Active Directory groups where group name like

Community
  • 1
  • 1
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
0

This should work:

using (var context = new PrincipalContext(ContextType.Domain, "my-domain"))
{
    var users = new PrincipalSearcher(new UserPrincipal(context)).FindAll()
        .OfType<UserPrincipal>()
        .Where(u => u.GetGroups().Any(g => g.Name.StartsWith("my value")))
        .Distinct()
        .Select(u => $"({u.Name}) {u.GivenName ?? "No GivenName"}, {u.Surname ?? "No Surname"}")
        .ToList();

    foreach (var u in users)
        Console.WriteLine(u);
}
rvnlord
  • 3,487
  • 3
  • 23
  • 32
  • Thaks for your answer. I have a lot of users and groups in `Active Directory` and I want to ask you if this approach will bring all users from `Active Directory` and then it will filter them. If yes I will have a problem with execution time and I will need a more optimal solution – roroinpho21 Dec 11 '16 at 18:31