user3442470 user3442470 - 2 months ago 5
C# Question

Iterate groups of user in AD and save them in list

I have a procedure that retrieves the user node out of AD:

public static void ConnectActiveDirectory()
List<string> lstGroups = new List<string>();
DirectoryEntry entry;
string user = "username";
string server = ConfigurationManager.AppSettings["ActiveDirectory.Server"];

entry = new DirectoryEntry(@"LDAP://" + server);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "sAMAccountName=" + user;
SearchResult result = searcher.FindOne();

The idea is to save all the groups in the list of strings without doing something like:

foreach (ResultPropertyValueCollection s in result.Properties.Values)
string groupname = null;

for (int i = 0; i < s.Count; i++)
dn = s[i].ToString();
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);

groupname = dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1);


Is there any method that I can use in 'DirectorySearcher' Class?

Also, is there any way to delete the first Hashtable? the adspath one from the SearchResult object.


Instead of parsing the distinguished name by yourself, you can use the DirectoryEntry object to ask AD for the display name. For example:

var directoryEntry = new DirectoryEntry(@"LDAP://address");
var directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = "samaccountname=user";
var result = directorySearcher.FindOne();
foreach (var i in result.Properties["memberOf"])
    var group = new DirectoryEntry(@"LDAP://" + i);