See if user is part of Active Directory group in C# + Asp.net See if user is part of Active Directory group in C# + Asp.net asp.net asp.net

See if user is part of Active Directory group in C# + Asp.net


With 3.5 and System.DirectoryServices.AccountManagement this is a bit cleaner:

public List<string> GetGroupNames(string userName){  var pc = new PrincipalContext(ContextType.Domain);  var src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc);  var result = new List<string>();  src.ToList().ForEach(sr => result.Add(sr.SamAccountName));  return result;}


Nick Craver's solution doesn't work for me in .NET 4.0. I get an error about an unloaded AppDomain. Instead of using that, I used this (we only have one domain). This will check groups of groups as well as direct group membership.

using System.DirectoryServices.AccountManagement;using System.Linq;...using (var ctx = new PrincipalContext(ContextType.Domain, yourDomain)) {    using (var grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, yourGroup)) {        bool isInRole = grp != null &&             grp            .GetMembers(true)            .Any(m => m.SamAccountName == me.Identity.Name.Replace(yourDomain + "\\", ""));    }}


The code below will work in .net 4.0

private static string[] GetGroupNames(string userName){    List<string> result = new List<string>();    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))    {        using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc))        {            src.ToList().ForEach(sr => result.Add(sr.SamAccountName));        }    }    return result.ToArray();}