Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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