检查当前用户是否是活动目录组的成员

我需要检查当前用户是否是活动目录组的成员。 我开始将当前用户设置如下。 现在我想知道如何检查这个CurrentUser是在活动目录组“CustomGroup”中

string CurrentUser = WindowsIdentity.GetCurrent().Name; 

您可以使用.NET 3.5 System.DirectoryServices.AccountManagement类。 有关详细信息,请参阅MSDN文章管理.NET Framework 3.5中的目录安全性主体 。 您可以使用以下内容:

 string CurrentUser = WindowsIdentity.GetCurrent().Name; PrincipalContext context = new PrincipalContext(ContextType.Domain, "Domain"); UserPrincipal upUser = UserPrincipal.FindByIdentity(context, CurrentUser); if(upUser != null) { if (upUser.IsMemberOf(context, IdentityType.SamAccountName, "CustomGroup")) { // The user belongs to the group } } 

在.NET 3.5或4中试试这个:

 PrincipalContext infPC = new PrincipalContext(ContextType.Domain, "domain", "login", "password"); UserPrincipal infUP = new UserPrincipal(infPC); PrincipalSearcher infPS = new PrincipalSearcher(); UserPrincipal foundUP; GroupPrincipal infGP = new GroupPrincipal(infPC); GroupPrincipal foundGP; string CurrentUser = WindowsIdentity.GetCurrent().Name; infUP.SamAccountName = CurrentUser; infPS.QueryFilter = infUP; foundUP = infPS.FindOne(); infGP.Name = "CustomGroup"; infPS.QueryFilter = infGP; foundGP = infPS.FindOne(); bool ismember = foundUP.IsMemberOf(foundGP);