2012-05-21 18 views
0

我有要求從Active Directory中檢索所有與用戶相關的信息。從Active Directory中檢索用戶管理器的代碼會引發異常

我的代碼檢索用戶的username,useremail, Full Name,但是當我嘗試檢索管理器的名稱時,代碼會拋出異常。

下面是我的代碼:

DataTable table = new DataTable(); 
table = dt; 

DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + domain); 

DirectorySearcher dSearch = new DirectorySearcher(dEntry); 
SearchResultCollection sResultcol; 

try 
{ 
    dSearch.Filter = "(objectCategory=organizationalUnit)"; 
    sResultcol = dSearch.FindAll(); 

    foreach (SearchResult sResult in sResultcol) 
    { 
     DirectoryEntry dUserEntry = new DirectoryEntry(); 
     DirectorySearcher dSearchUsers = new DirectorySearcher(dEntry); 

     SearchResultCollection sUserResults; 
     dSearchUsers.Filter = "(objectClass=User)"; 
     dSearchUsers.SearchScope = SearchScope.Subtree; 

     sUserResults = dSearchUsers.FindAll(); 

     foreach (SearchResult sUserResult in sUserResults) 
     { 
     DataRow dr = table.NewRow(); 
     string empCode = sResult.Properties["pager"].ToString(); 

     if (empCode.Length != 0) 
     { 
      dr["empcode"] = empCode; 
      string namee = sUserResult.Properties["samaccountname"][0].ToString(); 
      dr["name"] = namee; 
      string disname = sResult.Properties["distinguishedName"][0].ToString(); 
      dr["ou"] = disname; 
      string manager = sUserResult.Properties["manager"].Value.ToString(); 
      dr["manager"] = manager; 

      dt.Rows.Add(dr); 
     } 
     } 

     dUserEntry.Close(); 
    } 

    return dt; 
} 
catch (Exception ex) 
{ 
    throw new Exception("Error at retrieveUsers() : " +  ex.Message.ToString()); 
} 

我得到的異常

指數超出範圍。必須是非負值,並且小於集合的大小 。參數名稱:索引

當我嘗試獲取經理姓名。

根據Active Directory的結構,經理的姓名位於另一個選項卡中。

有沒有人有任何想法從Active Directory中的常規選項卡檢索數據?

請幫幫我。

在此先感謝。

回答

0

那麼,管理者的內容可能是對給定用戶的空 - 如果一個屬性沒有分配給它的值,在Active Directory中,它的.Properties[...]將是NULL - 讓你必須支票該訪問是不存在的屬性之前:

if(sUserResult.Properties["manager"] != null) 
{ 
    string manager = sUserResult.Properties["manager"].Value.ToString(); 
} 

另外:此內容只是管理者的DN(專有名稱) - 像

CN=Joe Blow,OU=Sales,OU=Europe,DC=yourcompany,DC=com 

它不包含管理器的「好」顯示名稱,或類似的東西....要獲取這些信息,您必須使用DN綁定到經理的用戶對象並獲取該數據。

另外:你有沒有設置你的數據表?在代碼中你展示,你只是創建DataTable - 但你不能建立在它裏面的任何列 - 所以像

dr["empcode"] = empCode; 

任何轉讓是註定要失敗,因爲在沒有列empcodeDataTable尚未...

+0

'System.DirectoryServices.ResultPropertyCollection'沒有包含'Properties'的定義,也沒有找到接受類型爲'System.DirectoryServices.ResultPropertyCollection'的第一個參數的擴展方法'Properties'你錯過了使用指令或程序集引用?這是當我使用你建議的代碼時得到的錯誤 –

+0

@MansiDesai:對不起 - 我有一個'.Properties'太多了 - 你能再試一次嗎? –

相關問題