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的情况下循环所有属性但是它不是实现我想要的方式。

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

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

 DirectoryEntry entry = result.GetDirectoryEntry(); 

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

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

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

 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()); } } } 

这就是你需要的吗?

遇到这个问题时,我自己也在考虑如何做到这一点。 相反,我发现了一种不同的方式,似乎工作正常。

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

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