Reputation: 33
I have a question that I have been searching for the answer for but can't seam to find one that works. I have an ASP.Net web application that I need to list all sub OU's of a specific OU. Does anyone now how would be best to go about this?
For example I want to list all the OU's under Users
and then enable the user to click on that OU and then see a list of user contained within that OU. I am able to list users within OU's already but I am currently unable to list the Sub OU's.
Here is the code that I have already;
DirectoryEntry Ldap = new DirectoryEntry("LDAP://ou=Users;ou=ASH;ou=Establishments;dc=domain;dc=com", aduser, adpass);
DirectorySearcher searcher = new DirectorySearcher(Ldap);
//specify that you search user only by filtering AD objects
searcher.Filter = "(objectClass=user)";
try
{
foreach (SearchResult result in searcher.FindAll())
{
//loop through each object and display the data in a table
DirectoryEntry DirEntry = result.GetDirectoryEntry();
TableRow tblRow = new TableRow();
TableCell tblcell_Username = new TableCell();
TableCell tblcell_displayName = new TableCell();
tblcell_Username.Text = DirEntry.Properties["SAMAccountName"].Value.ToString();
tblcell_displayName.Text = "";
tblRow.Controls.Add(tblcell_Username);
tblRow.Controls.Add(tblcell_displayName);
ADWeb_Tbl.Rows.Add(tblRow);
//DEBUG LINES
//On peut maintenant afficher les informations désirées
//Response.Write("Login: " + DirEntry.Properties["SAMAccountName"].Value);
}
}
catch (Exception ex)
{
Response.Write(ex.Source + "<br />");
Response.Write(ex.Message + "<br />");
Response.Write(ex.InnerException);
}
Does anyone have any suggestions?
Thank you for taking the time to read this question.
Upvotes: 1
Views: 3679
Reputation: 754240
Two main points:
if you want to find the organizational units - why are you searching for users?!?!? This makes no sense at all. Use this code:
DirectorySearcher searcher = new DirectorySearcher(Ldap);
// specify that you search for organizational units
searcher.Filter = "(objectCategory=organizationalUnit)";
searcher.SearchScope = SearchScope.SubTree; // search entire subtree from here on down
when you get the results from the searcher, you should try to avoid calling .GetDirectoryEntry()
on each single one of them. Specify which attributes you need in the DirectorySearcher
- and then use those attributes directly on the search results:
searcher.PropertiesToLoad.Add("sAMAccountName"); // and add any others you need
try
{
foreach (SearchResult result in searcher.FindAll())
{
TableRow tblRow = new TableRow();
TableCell tblcell_Username = new TableCell();
tblcell_Username.Text = result.Properties["SAMAccountName"].ToString();
Upvotes: 1