2017-06-16 90 views
2

我正在检查用户是否属于某个特定组。我的代码编写如下获取本地组的成员

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 

是否有此问题的任何可能的解决方案错误?

回答

2

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

您的代码与现有组正常工作。