Determin Group Membership (C#)
Posted: September 13, 2011 Filed under: .NET C#, Programming | Tags: .NET, Active directory, C#, Group Membership, linkedin Leave a comment »Determin Group Membership with System.DirectoryServices.AccountManagement in C#
You can determine group membership like this:
Remember to reference System.DirectoryServices.AccountManagement
using System.DirectoryServices.AccountManagement
public class GroupMembershipHelper
{
public static bool IsMemberOf(string username, string domain, string groupName)
{
using (var principalContext = new PrincipalContext(ContextType.Domain, domain))
{
using (UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, username))
{
if (userPrincipal != null)
{
PrincipalSearchResult groups = userPrincipal.GetAuthorizationGroups();
IEnumerable filteredGroups =
groups.Where(p => p.ContextType == ContextType.Domain && p.Guid != null && p is GroupPrincipal && ((GroupPrincipal)p).GroupScope == GroupScope.Universal)
.Select(p => p as GroupPrincipal);
return filteredGroups.Any(g => g.Name.Equals(groupName));
}
return false;
}
}
}
}