我正在尝试实现 LDAP 查询以收集我们拥有的关于用户的所有属性,而无需事先指定属性,我想将其显示在一个表中,因此使用了以下代码。如果我取消注释 search.PropertiesToLoad.Add("cn"); 这会起作用行并将显示我以相同方式添加的任何其他属性,但在我对所有属性进行全面搜索时不会显示。
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 时循环所有属性,但这并不是实现我想要的方法。
我知道我需要一些 try catch 和代码中的其他部分,这是一个粗略的草稿。
最佳答案
这可以使用 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));
}
关于c# - Active Directory 显示表格中的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1091115/