Skip to content

Instantly share code, notes, and snippets.

@steve-codemunkies
Created November 18, 2015 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save steve-codemunkies/3ff6e307b2ee9f4fde1b to your computer and use it in GitHub Desktop.
Save steve-codemunkies/3ff6e307b2ee9f4fde1b to your computer and use it in GitHub Desktop.
var username = "some.user.name";
var password = "some.password";
var entry = new DirectoryEntry("LDAP://rootDSE", username, password);
var nativeObject = entry.NativeObject;
var groups = new List<string>();
var groupsRegexp = new Regex("OU=Groups,");
var groupNameRegexp = new Regex("CN=(?<group>[\\w\\s]+)");
var searchPath = "LDAP://" + _entry.Properties["defaultNamingContext"].Value.ToString();
var search = new DirectorySearcher(searchPath) {Filter = $"(SAMAccountName={entry.Username})"};
search.PropertiesToLoad.Add("memberOf");
var result = search.FindOne();
var propertyCount = result.Properties["memberOf"].Count;
for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
{
var dn = (string)result.Properties["memberOf"][propertyCounter];
if (groupsRegexp.IsMatch(dn))
{
var matches = groupNameRegexp.Matches(dn);
foreach (Match match in matches)
{
groups.Add(match.Groups["group"].Value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment