Skip to content

How to check if a user is a member of an Active Directory group

I had to write some quick code for a project at work where I needed to audit a group of users and confirm if the user appeared in a predefined Active Directory group. There are a number of examples online, and I read some interesting approaches from authors at:

  1. Find what Active Directory groups a user is in
  2. Create a SQL Server view of your Active Directory users
  3. How to: (Almost) Everything in Active Directory via C#
  4. Searching the Directory
  5. Quick List for C# Code Examples

Below is a an early release of what I ended up using. Feedback if any would be appreciated.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.DirectoryServices;
using OrganizationNameAD;
namespace OrganizationNameAD
{
    class Program
    {
        static void Main()
        {
            String result = string.Empty;
            String strUserName = string.Empty;
            String strLDAP = string.Empty;
            String strGroupName = string.Empty;
            strUserName = "UserNameToCheck";
            strLDAP = "LDAP://OU=Organization,DC=Subdomain,DC=Domain,DC=TLD";
            strGroupName = "CN=GroupName,OU=GroupContainer,OU=Other,DC=Subdomain,DC=Domain,DC=TLD";
            result = GetAttribute(strLDAP, strUserName, "cn");
            Console.WriteLine("CN " + result);
            result = GetAttribute(strLDAP, strUserName, "memberOf");
            Console.WriteLine("memberOf " + result);
            result = IsGroupMember(strLDAP, strUserName, strGroupName);
            Console.WriteLine("Group " + result);
        }
        public static string GetAttribute(string strLDAPPath, string strsAMAccountName, string strAttribute)
        {
            string result = string.Empty;
            SearchResultCollection srcResults = null;
            try
            {
                DirectoryEntry de = new DirectoryEntry(strLDAPPath);
                DirectorySearcher ds = new DirectorySearcher(de);
                ds.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + strsAMAccountName + "))";
                srcResults = ds.FindAll();
                foreach (SearchResult srResult in srcResults)
                {
                    result = GetProperty(srResult, strAttribute);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                result = ex.Message;
            }
            finally
            {
                // To prevent memory leaks, call SearchResultCollection.Dispose()
                if (srcResults != null)
                {
                    srcResults.Dispose();
                    srcResults = null;
                }
            }
            return result;
        }
        public static string GetProperty(SearchResult srSearchResult, string strPropertyName)
        {
            string result = string.Empty;
            if (srSearchResult.Properties.Contains(strPropertyName))
            {
                result = srSearchResult.Properties[strPropertyName][0].ToString();
            }
            else
            {
                result = "Attribute not found";
            }
            return result;
        }
        public static string IsInActiveDirectory(string strLDAPPath, string strsAMAccountName)
        {
            string result = string.Empty;
            SearchResult srResult = null;
            try
            {
                DirectoryEntry de = new DirectoryEntry(strLDAPPath);
                DirectorySearcher ds = new DirectorySearcher(de);
                ds.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + strsAMAccountName + "))";
                srResult = ds.FindOne();
                if (srResult != null)
                {
                    result = "Yes";
                }
                else
                {
                    result = "No";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                result = ex.Message;
            }
            return result;
        }
        public static string IsGroupMember(string strLDAPPath, string strsAMAccountName, string strGroupName)
        {
            string result = "No";
            SearchResultCollection srcResults = null;
            SearchResult srResult = null;
            ResultPropertyValueCollection rpvcResult = null;
            try
            {
                DirectoryEntry de = new DirectoryEntry(strLDAPPath);
                DirectorySearcher ds = new DirectorySearcher(de);
                ds.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + strsAMAccountName + "))";
                srResult = ds.FindOne();
                // Create a ResultPropertyValueCollection object to get the values for the
                // memberOf attribute for this user.
                string propertyName = "memberOf";
                rpvcResult = srResult.Properties[propertyName];
                Console.WriteLine(rpvcResult[0].ToString());
                foreach (Object propertyValue in rpvcResult)
                {
                    if (propertyValue.ToString() == strGroupName)
                    {
                        result = "Yes";
                    }
                }
            }
            catch (Exception t)
            {
                Console.WriteLine(t.Message);
            }
            finally
            {
                // To prevent memory leaks, call SearchResultCollection.Dispose() manually
                if (srcResults != null)
                {
                    srcResults.Dispose();
                    srcResults = null;
                }
            }
            return result;
        }
    }
}