Wednesday 11 June 2014

Get All AD Groups using LDAP in C#


Issue: LDAP Query not pulling all the Active Directory Groups (including subgroups) available in the given domain.
Solution:
To retrieve a set of results that is larger than 1000 items, you must set SizeLimit to its default value (zero) and set PageSize to a value that is less than or equal to 1000.

public static DataTable GetAllActiveDirectoryGroups(string ldapServer, string ldapUserName, string ldapPassWord)
{
DataTable dt = new DataTable();
DataRow dr;
DirectoryEntry de = new DirectoryEntry(ldapServer);
de.Username = ldapUserName;
de.Password = ldapPassWord;
DirectorySearcher deSearch = new DirectorySearcher(de.Path);
SearchResultCollection results;
dt.Columns.Add("GroupName");
try
{
deSearch.Filter = ("(&(objectCategory=group))");
deSearch.SearchScope = SearchScope.Subtree;
//deSearch.SizeLimit = 10000;
deSearch.PageSize = 1000;
results = deSearch.FindAll();
foreach (SearchResult result in results)
{
dr = dt.NewRow();
dr["GroupName"] = result.Properties["cn"][0].ToString();
dt.Rows.Add(dr);
}
de.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (deSearch != null)
{
deSearch.Dispose();
}
if (de != null)
{
de.Dispose();
}
}
return dt;
}
http://msdn.microsoft.com/en-us/library/ms180880(v=vs.90).aspx