This project is read-only.
1
Vote

New Method: Find users in a group

description

I remember using this code years ago, and I just found it again. I added a new method that I use from time to time - how to find all the users in an AD group.

To do that I had to change the .NET properties to use at least 3.5 (I used 4.5), then added a reference to the following.

using System.DirectoryServices.AccountManagement;

Then it was a quick change to the User.asmx in the project to add the following...worked great.
       [WebMethod(Description = "Returns a generic list of the Active Directory users that belong to a group.")]
        public List<string> GetGroupMembers(string groupName)
        {
            List<string> lstResult = new List<string>();

            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

            GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);

            try
            {
                // if found....
                if (group != null)
                {
                    // iterate over members
                    foreach (Principal p in group.GetMembers())
                    {
                        // do whatever you need to do to those members
                        lstResult.Add(p.DisplayName);
                    }
                }
                else
                {

                    lstResult.Add("User Not Found In Active Directory");
                }
            }


            catch (Exception ex)
            {
                lstResult.Add("An error was thrown by the LDAP Web Service.  The Error was \r\n" + ex.Message.ToString());
            }

            return lstResult;
        }

comments