Active Directory : Get all "Security Group"
I'd like to g开发者_开发问答et all groups "Security Groups" available in the Active Diectory.
Any idea ?
Thanks,
Since you're on .NET 3.5 or higher, you can use a PrincipalSearcher
and a "query-by-example" principal to do your searching:
// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// define a "query-by-example" principal - here, we search for a GroupPrincipal
// with the security group flag set
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
qbeGroup.IsSecurityGroup = true;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement
Try this way
DirectoryEntry ent1 = new DirectoryEntry("LDAP://" + _path,
"adminUser", "***********");
DirectorySearcher dSearch = new DirectorySearcher(ent1);
dSearch.Filter = "(&(objectClass=group))";
dSearch.SearchScope = SearchScope.Subtree;
SearchResultCollection results = dSearch.FindAll();
List<string> groupNames = new List<string>();
for (int i = 0; i < results.Count; i++)
{
DirectoryEntry de = results[i].GetDirectoryEntry();
groupNames.Add(de.Name.Replace("CN=", ""));
}
It's working for me :)
精彩评论