Active Directory: Check if a member is in a group


Overview

Here is a C# function that will return a bool of whether the user is in the specified AD group. This does not return the entire group in the code so it should perform even on large groups.

This will require a reference to the System.DirectoryServices.AccountManagement Nuget package.

using System.DirectoryServices.AccountManagement;

public bool UserIsInGroup(string networkId, string groupName) 
{
    bool userInGroup = false;

    using (var context = new PrincipalContext(ContextType.Domain))
    {
        try
        {
            // Find the user by their network ID
            var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, networkId);

            if (user != null)
            {
                // Find the group by its name
                var group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, groupName);

                if (group != null)
                {
                    // Check if the user is a member of the group
                    userInGroup = user.IsMemberOf(group);
                }
            }
        }
        catch (Exception ex)
        {
            // Handle any exceptions that occur during the query
            // For example, if the user or group doesn't exist, or if the domain controller is not available
            Console.WriteLine(ex.Message);
        }
    }

    return userInGroup;
}