获取本地组的成员

Get the Members of the local group

我正在检查用户属于特定组的天气。我的代码是这样写的

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;
    }

但是我遇到了一个看起来像这样的错误

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

这个问题有什么可能的解决方案吗?

groupPrincipal 为空,因为您正在搜索的组 ('TestGrp1') 从未找到 - 很可能不存在。

您的代码适用于现有群组。