Search code examples
c#active-directorydirectoryentryprincipalcontext

Get the Members of the local group


I am checking weather the user belongs to a particular group. My code is written as follows

public static  bool IsInGroup(string user, string group)
    {
        Console.WriteLine("The user name and group name is {0} {1}", user, group); //Check the parameter values

        bool result = false;
        PrincipalContext context = new PrincipalContext(ContextType.Domain);
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context,user);
        GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(context, group);
        if (userPrincipal != null)
        {
            if (userPrincipal.IsMemberOf(groupPrincipal))
            {
                result = true;
            }
        }
        return result;
    }

But I am facing an error which looks like this

The user name and group name is sampat TestGrp1
Value cannot be null.
Parameter name: group

Is there any possible solution for this issue?


Solution

  • groupPrincipal is null because the group are you searching for ('TestGrp1') is never found - most likely it does not exist.

    Your code works correctly with an existing group.