2017-06-16 45 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')從未找到 - 很可能它不存在。

您的代碼與現有組正常工作。