2013-06-25 90 views
1

我有一個問題,我一直在尋找答案,但無法找到可行的答案。我有一個ASP.Net Web應用程序,我需要列出特定OU的所有子OU。現在有人會怎麼做最好的呢?列出aspx頁面中的所有組織單位(OU)和子OU的

例如,我想列出Users下的所有OU,然後啓用用戶單擊該OU,然後查看該OU中包含的用戶列表。我能夠在OU中列出用戶,但我目前無法列出子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); 
} 

有沒有人有任何建議?

感謝您花時間閱讀此問題。

+0

所以會發生什麼,當你運行你的代碼? – codeape

回答

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

我發佈的代碼只是我目前用來獲取AD用戶列表的一個例子。我不認爲SMSAccountName適用於OU的?另外,當我運行這段代碼時,我得到以下錯誤:對象引用未設置爲對象的實例。 任何想法? – tparky

相關問題