Active Directory显示表中的所有属性

时间:2009-07-07 08:53:17

标签: c# active-directory

我正在尝试实现一个LDAP查询来收集我们有关用户的所有属性而不事先指定属性,我想在表中显示这个,所以使用下面的代码。如果我取消注释search.PropertiesToLoad.Add(“cn”); line并将以相同的方式显示我添加的任何其他属性,但在我对所有属性进行完全搜索时则不会。

DirectoryEntry myLdapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(myLdapConnection);

search.CacheResults = true;
//search.PropertiesToLoad.Add("cn");

SearchResultCollection allResults = search.FindAll();
DataTable resultsTable = new DataTable("Results");

//add columns for each property in results
foreach (string colName in allResults.PropertiesLoaded)
    resultsTable.Columns.Add(colName, colName.GetType());

//loop to add records to DataTable
foreach (SearchResult result in allResults)
{
    int tmp = result.Properties.Count;
    DataRow row = resultsTable.NewRow();
    foreach (string columnName in search.PropertiesToLoad)
    {
        if (columnName.Equals("lastlogon"))
        {
            if (result.Properties.Contains(columnName))
                row[columnName] = ConvertDate(result.Properties[columnName].ToString());
            else
                row[columnName] = "";
        }
        else
        {
            if (result.Properties.Contains(columnName))
                row[columnName] = result.Properties[columnName][0].ToString();
            else
                row[columnName] = "";
        }
    }
    resultsTable.Rows.Add(row);
}

gridResults.DataSource = resultsTable;

问题似乎与

有关
foreach (string colName in allResults.PropertiesLoaded)
    resultsTable.Columns.Add(colName, colName.GetType());

我希望在没有指定PropertiesToLoad的情况下循环所有属性但是它不是实现我想要的方式。

我知道我在代码中需要一些尝试捕获和其他位,但这是一个草稿。

3 个答案:

答案 0 :(得分:12)

可以使用DirectoryEntry完成此操作,但我不认为SearchResultCollection包含所有字段。
尝试为每个搜索结果创建一个DirectoryEntry,它应该具有所有活动目录属性:

DirectoryEntry entry = result.GetDirectoryEntry();

另外,请注意,在活动目录中,每个属性都可以有多个值(如MemberOf字段),因此您也必须迭代它们。
我写了一个类似的方法,但是我选择了一个带有键/值的List(它似乎比WCF更易于管理。ILookup将是最佳的,但我无法让它在这里工作)。在这里,它是从try / catch / using

中删除的
var list = new List<KeyValuePair<string, string>>();
foreach (PropertyValueCollection property in entry.Properties)
   foreach (object o in property)
   {
       string value = o.ToString();
       list.Add(new KeyValuePair<string, string>(property.PropertyName, value));
   }

答案 1 :(得分:11)

您可以通过这种方式遍历所有属性:

foreach (SearchResult searchResult in allResults)
{
  foreach (string propName in searchResult.Properties.PropertyNames)
  {
    ResultPropertyValueCollection valueCollection =
    searchResult.Properties[propName];
    foreach (Object propertyValue in valueCollection)
    {
    Console.WriteLine("Property: " + propName + ": " + propertyValue.ToString());
    }
  }
}

这就是你需要的吗?

答案 2 :(得分:1)

在看自己如何做的时候遇到了这个帖子。 相反,我发现了一种不同的方式,似乎工作正常。

return ((DirectoryEntry)UserPrincipal.Current.GetUnderlyingObject()).Properties.PropertyNames;

无论如何,它的装载完美地在Combobox中找到。 只是让其他人遇到这个帖子。