0

我需要从 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 的常规以外的选项卡中检索数据?

请帮我。

提前致谢。

4

1 回答 1

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...

于 2012-05-21T05:04:43.870 回答