列出aspx页面中的所有组织单位(OU)和子OU

时间:2013-06-25 08:24:05

标签: c# active-directory ldap

我有一个问题,我一直在寻找答案,但不能找到一个有效的问题。我有一个ASP.Net Web应用程序,我需要列出特定OU的所有子OU。现在有人怎么会这样做?

例如,我想列出Users下的所有OU,然后让用户单击该OU,然后查看该OU中包含的用户列表。我能够在OU中列出用户,但我目前无法列出Sub OU。

这是我已经拥有的代码;

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);
}

有人有任何建议吗?

感谢您抽出宝贵时间阅读此问题。

1 个答案:

答案 0 :(得分:1)

两个要点:

  1. 如果你想找到组织单位 - 你为什么要搜索用户?!?!?这毫无意义。使用此代码:

    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
    
  2. 当您从搜索者那里得到结果时,您应该尽量避免在每一个上面调用.GetDirectoryEntry()。在DirectorySearcher中指定所需的属性 - 然后直接在搜索结果中使用这些属性:

    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();