Find a user's Active Directory groups.

I like simple solutions. Fortunately the .Net Framework API's are slowly evolving to make life simpler for the architect and programmer. One new .Net 3.5 framework library which I am very happy with is System.DirectoryServices.AccountManagement. Have a look at how simple it is to find the groups an AD user belongs to.

Add a reference to System.DirectoryServices and System.DirectoryServices.AccountManagement.

 

using System;
using System.Collections.Generic;
using System.Linq;

using System.DirectoryServices.AccountManagement;

namespace DetermineUserGroupsConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initializes a new instance of the System.DirectoryServices.AccountManagement.PrincipalContext
            //class with the specified context type.
            PrincipalContext principalContext = new PrincipalContext(ContextType.Machine);
            UserPrincipal userPrinciple = UserPrincipal.FindByIdentity(principalContext, IdentityType.Name, "EHS\\jean");

            // Select a list of group names from the PrincipalSearchResult<Principal>
            var userGroups = from userGroup in userPrinciple.GetGroups()
                             select userGroup.Name;
            
            foreach (string groupName in userGroups)
            {
                System.Console.WriteLine(groupName);
            }

            System.Console.ReadKey();
        }
    }
}

 

Have a look at the MSDN site or codeproject for further information on this topic.

Hope this was helpfull. 

Published 19 April 2010 01:19 by jean
Filed under:

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)