Skip to content

Instantly share code, notes, and snippets.

@rsds143
Created May 13, 2011 15:25
Show Gist options
  • Save rsds143/970732 to your computer and use it in GitHub Desktop.
Save rsds143/970732 to your computer and use it in GitHub Desktop.
collection of tidbits I've pulled together
public class ActiveDirectoryGroupFinder
{
public string GetPrimaryGroup(DirectoryEntry aEntry)
{
var primaryGroupID = (int)aEntry.Properties["primaryGroupID"].Value;
var objectSid = (byte[])aEntry.Properties["objectSid"].Value;
var escapedGroupSid = new StringBuilder();
// Copy over everything but the last four bytes(sub-authority)
// Doing so gives us the RID of the domain
for (uint i = 0; i < objectSid.Length - 4; i++)
{
escapedGroupSid.AppendFormat("\\{0:x2}", objectSid[i]);
}
//Add the primaryGroupID to the escape string to build the
// SID of the primaryGroup
for (uint i = 0; i < 4; i++)
{
escapedGroupSid.AppendFormat("\\{0:x2}",
(primaryGroupID & 0xFF));
primaryGroupID >>= 8;
}
var searcher = new DirectorySearcher
{
Filter = "(&(objectCategory=Group)(objectSID=" +
escapedGroupSid + "))"
};
searcher.PropertiesToLoad.Add("cn");
return
searcher.FindOne().Properties["cn"][0].ToString();
}
public IList<string> GetGroups(string lDAPName, IList<string> foundCollection)
{
using (var directoryEntry = new DirectoryEntry(lDAPName))
{
var groupsIter = directoryEntry.Properties["memberOf"].GetEnumerator();
while (groupsIter.MoveNext())
{
if (groupsIter.Current == null) continue;
var groupLDAPName = groupsIter.Current.ToString();
using (var groupDirectoryEntry = new DirectoryEntry("LDAP://" + groupLDAPName))
{
using (var groupSearcher = new DirectorySearcher(groupDirectoryEntry))
{
groupSearcher.SearchScope = SearchScope.Base;
groupSearcher.PropertiesToLoad.Add("cn");
var groupResult = groupSearcher.FindOne();
var groupName = groupResult.Properties["cn"][0].ToString();
if (foundCollection.Contains(groupName)) continue;
foundCollection.Add(groupName);
}
}
GetGroups(String.Format("LDAP://{0}", groupLDAPName), foundCollection);
}
}
return foundCollection;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment