2009-07-07 24 views
6

我想实现一个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了,但它不会是他们的方式来实现我想要的。

我知道我需要一些尝试渔获物和其他位代码作为然而,这是一个粗略的草稿。

回答

12

这可以通过使用DirectoryEntry做,但我不认为SearchResultCollection有各个领域。
尝试创建为每个搜索结果的DirectoryEntry,它应该有所有的Active Directory特性:

DirectoryEntry entry = result.GetDirectoryEntry(); 

另外,还要注意的是,在活动目录中的每个属性可以有多个值(如成员字段),所以你也必须迭代它们。
我已经写了一个类似的方法,但是我选择了与键/值的List(它似乎在WCF更易于管理。ILookup将是最佳的,但我无法得到它在这里工作)。在这里它是,从尝试/捕获/使用剥离

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

您可以通过所有属性重复这样:

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

是你需要什么?

+0

感谢!!!!!!!!! – Sak 2017-04-17 08:57:09

1

来到这个线程,一边看自己如何做到这一点。 相反,我发现了一种不同的方式,并且似乎工作正常。

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

无论如何,它的加载完全可以在Combobox中找到。 只要介绍任何人遇到此线程。

+0

如果您的评论将UserPrincipal与DirectorySearcher相关联或相关,这可能对我更有帮助。我可能对这个对象不够了解,但是我看不到有效的对象类型,而且我无法解决这个问题。 – Taersious 2015-08-11 14:20:59

相关问题