Thursday, August 27, 2009

How to get the users of a Active Directory group in SharePoint.

While adding a new user to a SharePoint group, you can enter Active Directory group name, so that all the users inside the AD group can access the SharePoint site, which is completely a out-of-box functionality in SharePoint. But there might be requirement where we need to access users of a specific AD group independently to perform some action against each of them.

Below is the code snippet in c# to acces each users details of a specific Active Directory group.

NameSpace: using Microsoft.SharePoint.Utilities;

bool reachMaxCount;

// objSPWeb is the SPWeb object
SPPrincipalInfo[] adGroupUsers = SPUtility.GetPrincipalsInGroup(objSPWeb, "DomainName\\GroupName", 100, out reachMaxCount);

foreach (SPPrincipalInfo objAdUserInfo in adGroupUsers)
      string loginName = objAdUserInfo.LoginName;
      string displayName = objAdUserInfo.DisplayName;
      string emailId = objAdUserInfo.Email;

**************Fetch the AD users using LDAP**************

public void GetADUsersInADGroup(string domainName,string groupName)


string userNames = "Users : " + Environment.NewLine;

string anyADUserID = "samarendra";

string anyADUserPassword = "password";
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domainName, anyADUserID, anyADUserPassword);

DirectorySearcher dSearch = new DirectorySearcher(entry);

dSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";

SearchResult results = dSearch.FindOne();
if (results != null)

DirectoryEntry objGroup = new DirectoryEntry(results.Path, anyADUserID, anyADUserPassword, AuthenticationTypes.Secure);

System.DirectoryServices.PropertyCollection pcoll = objGroup.Properties;

for (int count = 0; count < pcoll["member"].Count; count++)


DirectoryEntry deUser = new DirectoryEntry("LDAP://" + domainName + "/" + pcoll["member"][count].ToString(), anyADUserID, anyADUserPassword, AuthenticationTypes.Secure);

userNames += deUser.Properties["cn"].Value + Environment.NewLine; // cn is for login Name





Samarendra Swain

No comments:

Post a Comment