Home
Manage Your Code
Snippet: Get Active Directory Group Members and See if User Belongs to it (C#)
Title: Get Active Directory Group Members and See if User Belongs to it Language: C#
Description: This code gets all the members of a group and checks to see if the logged in user is a member of the group. Views: 588
Author: Roger Johnson Date Added: 1/16/2008
Copy Code  
1    using System.DirectoryServices;
2    using System.Collections.Specialized;
3
4    public bool IsMember(string Group)
5    {
6        StringCollection groupMembers = this.GetGroupMembers(Group);
7        foreach (string strMember in groupMembers)
8        {
9            if ("[NetBios Domain Name]\\" + strMember == HttpContext.Current.User.Identity.Name.ToString())
10            {
11                return true;
12            }
13        }
14        return false;
15    }
16    public StringCollection GetGroupMembers(string strGroup)
17    {
18        StringCollection groupMemebers = new StringCollection();
19        try
20        {
21            DirectoryEntry ent = new DirectoryEntry("LDAP://DC=DomainName,DC=com");
22            DirectorySearcher srch = new DirectorySearcher("(CN=" + strGroup + ")");
23            SearchResultCollection coll = srch.FindAll();
24            foreach (SearchResult rs in coll)
25            {
26                ResultPropertyCollection resultPropColl = rs.Properties;
27                foreach (Object memberColl in resultPropColl["member"])
28                {
29                    DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);
30                    System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;
31                    object obVal = userProps["sAMAccountName"].Value;
32                    if (null != obVal)
33                    {
34                        groupMemebers.Add(obVal.ToString());
35                    }
36                }
37            }
38        }
39        catch (Exception ex)
40        {
41            throw;
42        }
43        return groupMemebers;
44    }