Getting Active Directory Groups from User Account

Our object is to get all active directory groups for a user. Here is the sample code in C#.

First Add reference for following namespaces and import in code
using System.DirectoryServices;

Here I created method getGroupsFromUser which takes 4 args.
First RootPath: Domain Root (Generally Domainname.com)
Second and Third (user and password) to connect Active directory. If current user is able to connect then no need to pass.
Fourth argument is the user name for which we have to get all AD groups.

Code:

protected void Page_Load(object sender, EventArgs e)
{
getGroupsFromUser("LDAP://DomainName.com","","","Administrator");
}

private ArrayList getGroupsFromUser(string rootpath, string userName, string pwd, string strUser)
{
ArrayList groupMembers = new ArrayList();
DirectoryEntry de;
DirectorySearcher ds;
if (userName != "")
{
de = new DirectoryEntry(rootpath,userName,pwd);
ds = new DirectorySearcher(de);
}
else
{
ds = new DirectorySearcher(rootpath);
}

// find all users in this group

ds.Filter = String.Format("(&(samaccountname={0})(objectClass=person))", strUser);
ds.PropertiesToLoad.Add("memberof");
try
{
foreach (SearchResult sr in ds.FindAll())
{
foreach (string str in sr.Properties["memberof"])
{
string str2 = str.Substring(str.IndexOf("=") + 1, str.IndexOf(",") - str.IndexOf("=") - 1);
groupMembers.Add(str2);
Response.Write(str2 + "<br/>");
}
}
}
catch
{
//ignore if any properties found in AD
}
return groupMembers;
}

1 comment:

  1. Wow!. Being struggling to get this working and your code worked first time. Awesome, thanks!!

    ReplyDelete