Finding out if user is a member of Active Directory Group can be done using following snippet of code
Method 1: using PrincipalContext
Method 2:using DirectoryEntry
It has become appallingly obvious that our technology has exceeded our humanity. Albert Einstein
Method 1: using PrincipalContext
public static bool IsGroupMember(string domain, string group, string login)
{
bool result = false;
PrincipalContext context = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, login);
GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(context, group);
if (userPrincipal != null)
{
if (userPrincipal.IsMemberOf(groupPrincipal))
{
result = true;
}
}
return result;
}
Note: This is easy to use but only works based on specific domainMethod 2:using DirectoryEntry
public static bool IsGroupMember(Logger logger, string group, string userName)
{
string strSid;
bool result = false;
clsLookupAccountName.GetAccountSid(userName, out strSid);
DirectoryEntry rootDSE = new DirectoryEntry("GC://RootDSE");
string rootDomainNamingContext = rootDSE.Properties["rootDomainNamingContext"].Value.ToString();
string filter = "(&(objectCategory=user)(objectSid=" + strSid + "))";
DirectorySearcher searcher = new DirectorySearcher("GC://" + rootDomainNamingContext);
searcher.Filter = filter;
searcher.PropertiesToLoad.Clear();
searcher.PropertiesToLoad.Add("distinguishedName");
SearchResult sr = searcher.FindOne();
string userDN = sr.Properties["distinguishedName"][0].ToString();
DirectoryEntry groupEntry = new DirectoryEntry(group);
PropertyValueCollection pvc = groupEntry.Properties["member"];
result = pvc.Contains(userDN);
return result;
}
Note: This requires you to understand AD objects and its properties. Allows you to search universallyIt has become appallingly obvious that our technology has exceeded our humanity. Albert Einstein




