Question

I have to check usergroups of LDAP Active Directory for a specific user in C#. Mean I pass this username to a method and it returns me list of group from that user belongs. Can You Please help me in this. Im Searching alot But Everytime get new error.

LDAP Path: 192.168.1.4

Domain Name: Arslan

UserName: ArslanP

Password: testad

Was it helpful?

Solution

Since you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Managing Directory Security Principals in the .NET Framework 3.5

Basically, add a reference to the assembly System.DirectoryServices.AccountManagement, and then you can define a domain context and easily find users and/or groups in AD:

using System.DirectoryServices.AccountManagement;

public List<GroupPrincipal> GetGroupsForUser(string username)
{
  List<GroupPrincipal> result = new List<GroupPrincipal>();

  // set up domain context - if you do a lot of requests, you might
  // want to create that outside the method and pass it in as a parameter
  PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

  // find user by name
  UserPrincipal user = UserPrincipal.FindByIdentity(username);

  // get the user's groups
  if(user != null)
  {
     foreach(GroupPrincipal gp in user.GetAuthorizationGroups())
     {
         result.Add(gp);
     }    
  }

  return result;
}

The new S.DS.AM makes it really easy to play around with users and groups in AD:

OTHER TIPS

This related question may help you:

Get List of Users From Active Directory In A Given AD Group

It asks the reverse question, which is how to qet a list of users when you know the group, but other answers may be of use to you as well.

See also the answer to this question:

How to get all the AD groups for a particular user?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top