I'am back with my Active Directory tool...
I'am trying to list the groups in the "member of" attribute of a user. Below is the function I use:
public static DataTable ListGroupsByUser(string selectedOu)
{
DataTable groupListByUser = new DataTable();
String dom = "OU=" + selectedOu + ",OU=XXX,DC=XXX,DCXXX,DC=XXX,DC=XXX";
DirectoryEntry directoryObject = new DirectoryEntry("LDAP://" + dom);
DataColumn column;
DataRow row;
column = new DataColumn();
column.ColumnName = "ID";
groupListByUser.Columns.Add(column);
column = new DataColumn();
column.ColumnName = "User";
groupListByUser.Columns.Add(column);
column = new DataColumn();
column.ColumnName = "Groups";
groupListByUser.Columns.Add(column);
int i = 1;
foreach (DirectoryEntry child in directoryObject.Children)
{
row = groupListByUser.NewRow();
groupListByUser.Rows.Add(row);
row["ID"] = i++;
if (child.Properties["memberOf"].Value != null)
{
row["User"] = child.Properties["sAMAccountName"].Value.ToString();
row["Groups"] = child.Properties["memberOf"].Value.ToString();
}
else
{
row["Groups"] = "blabla";
}
}
return groupListByUser;
}
It returns the right group for users belonging to only one group. As soon as There's more than one group, it returns System.Object[].
How can I do to see all groups ?
The problem is your Properties["memberOf"].Value.ToString()
.
I made a little investigation and this code worked for me:
var memberGroups = child.Properties["memberOf"].Value;
if (memberGroups.GetType() == typeof(string))
{
row["Groups"] = (String)memberGroups;
}
else if (memberGroups.GetType().IsArray)
{
var memberGroupsEnumerable = memberGroups as IEnumerable;
if (memberGroupsEnumerable != null)
{
var asStringEnumerable = memberGroupsEnumerable.OfType<object>().Select(obj => obj.ToString());
row["Groups"] = String.Join(", ", asStringEnumerable);
}
}
else
{
row["Groups"] = "No group found.";
}
It's not very cute but it works and gives room for further improvements. ;-)
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
var groups = user.GetGroups();
// or there's also:
//var authGroups = userByEmail.GetAuthorizationGroups()
}
The calls to GetGroups()
or GetAuthorizationGroups()
will return nested group membership, too - so no need for you to hunt those nested memberships anymore!
The new S.DS.AM makes it really easy to play around with users and groups in AD!
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