We are using the following code to get the groups of an active directory user.
StringCollection groups = new StringCollection();
try
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, userName, password))
{
//find user roles
UserPrincipal user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, loginUserName);
if (user != null)
{
DirectoryEntry de = (DirectoryEntry)user.GetUnderlyingObject();
object obGroups = de.Invoke("Groups");
foreach (object ob in (IEnumerable)obGroups)
{
DirectoryEntry obGpEntry = new DirectoryEntry(ob);
groups.Add(obGpEntry.Name);
}
}
}
}
catch (Exception e)
{
}
This is working almost as expected. But while we checking the users with Domain Users
group, the method didn't return the group name. Some users are only with this Domain Users
group and while we calling this method for such users its returning an empty group.
Any suggestions please..