I'd like to use AccountManagement to list all the groups in an Organizational Unit.
The following snippet works with DirectoryServices but I would have to instanciate GroupPrincipal with the DirectoryEntry path in the result (which feels like a dirty fix).
DirectoryEntry root = new DirectoryEntry("LDAP://OU=Marketing,OU=Operations,OU=Applications,DC=mycompany,DC=local")
DirectorySearcher ds = new DirectorySearcher(root);
ds.Filter = "(objectCategory=group)";
SearchResultCollection results = ds.FindAll();
Has anyone an idea?
Thanks!
In .NET C#, we can get the list of AD user group memberships using two methods. In first method, we can get nested groups from the constructed attribute TokenGroups, it requires the dll reference System.DirectoryServices (It is available from .NET Framework 2.0).
To add a user to a group, you should add the UserPrincipal object that holds the reference of a user to this enumeration. And the same logic for removing a user from a group: you must remove that user from the enumeration. But, do not forget to execute the Save method of GroupPrincipal after making changes.
This overloaded method only returns the groups of which the principal is directly a member; no recursive searches are performed. Recursive search results are available for user principal objects. For more information, see the GetAuthorizationGroups method.
UserPrincipal insUserPrincipal = (UserPrincipal)lbUsers.SelectedItem; insUserPrincipal.SetPassword ( "12345678" ); MessageBox.Show ( "Password changed." ); You can get the members of a group from the Members property of the GroupPrincipal object. You can use this property as an enumeration.
You can set the PrincipalContext
to the OU where you want to start the search and use the PrincipalSearcher
-class in System.DirectoryService.AccountManagement
to accomplish what you need, like this:
PrincipalContext yourOU = new PrincipalContext(ContextType.Domain, "mycompany.local", "OU=Marketing,OU=Operations,OU=Applications,DC=mycompany,DC=local");
GroupPrincipal findAllGroups = new GroupPrincipal(yourOU, "*");
PrincipalSearcher ps = new PrincipalSearcher(findAllGroups);
foreach(var group in ps.FindAll())
{
Console.WriteLine(group.DistinguishedName);
}
Console.ReadLine();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With