Get all the user's groups from active directory in C#

3.6k views Asked by At

I'm trying to get all the user's groups in the active directory with c# code.

This is my code:

private List<GroupPrincipal> GetGroups()
{
    string userName = User.Identity.Name;
    string host = Request.Url.Host.ToLower();
    List<GroupPrincipal> result = new List<GroupPrincipal>();

    UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, host), IdentityType.SamAccountName, userName);
    foreach (GroupPrincipal group in user.GetGroups())
    {
        result.Add(group);
    }
    return result;
}

I receive an error on the row that starts with UserPrincipal user that says that the server could not be connected. I'm running my code from the server itself so I can connect it.

What am i doing wrong?

Thank you in advance!

1

There are 1 answers

0
coder On

To connect with Active Directory, Create PrincipalContext object.

PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "MyDomain", 
                                   "DC=MyDomain,DC=com");

Code to get all Groups: Create GroupPrincipal object and call SearchGroups() which returns list of all groups of given domain.

     private void ListGroups(){
       GroupPrincipal insGroupPrincipal = new GroupPrincipal(insPrincipalContext);
       insGroupPrincipal.Name = "*";
       SearchGroups(insGroupPrincipal);}

    private void SearchGroups(GroupPrincipal parGroupPrincipal)
    {
        List<Principal> oList = new List<Principal>();
        PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();
        insPrincipalSearcher.QueryFilter = parGroupPrincipal;
        PrincipalSearchResult<Principal> results = insPrincipalSearcher.FindAll();
        foreach (Principal p in results)
        {
            oList.Add(p);
        }
    }

This link will also help you - http://www.codeproject.com/Articles/38344/Using-System-DirectoryServices-AccountManagement