开发者

Limiting the attributes returned in an LDAP query

开发者 https://www.devze.com 2023-04-09 20:05 出处:网络
How do I limit the attributes that are returned in an LDAP query through System.DirectoryServices? I have been using a DirectorySearcher and adding the properties that I want to DirectorySearcher.Pr

How do I limit the attributes that are returned in an LDAP query through System.DirectoryServices?

I have been using a DirectorySearcher and adding the properties that I want to DirectorySearcher.PropertiesToLoad. The problem is that this just makes sure that the added properties are included in the DirectoryEntry.Properties as well as some default list. Is there any way to specify the only properties that you want returned?

DirectoryEntry base = new DiectoryEntry(rootPath, null, null, AuthenticationTypes.FastBind);
DirectorySearcher groupSearcher = new DirectorySearcher(base);
groupSearcher.Filter = "(ob开发者_运维技巧jectClass=group)";
groupSearcher.PropertiesToLoad.Add("distinguishedName");
groupSearcher.PropertiesToLoad.Add("description");
foreach (SearchResult groupSr in groupDs.FindAll())
...

Inside the foreach loop when I get the group DirectoryEntry there are about 16 different properties that I can access not just the two that I specified (distinguishedName, description)


The thing you're limiting there are the properties that will be available / filled in your SearchResult objects - which you can access directly in your foreach loop:

DirectoryEntry baseEntry = new DirectoryEntry(rootPath, null, null, AuthenticationTypes.FastBind);

DirectorySearcher groupSearcher = new DirectorySearcher(baseEntry);
groupSearcher.Filter = "(objectClass=group)";

groupSearcher.PropertiesToLoad.Add("distinguishedName");
groupSearcher.PropertiesToLoad.Add("description");

foreach (SearchResult groupSr in groupSearcher.FindAll())
{
   if(groupSr.Properties["description"] != null && groupSr.Properties["description"].Count > 0)
   {
      string description = groupSr.Properties["description"][0].ToString();
   }

  .....
} 

You cannot limit the properties on the actual DirectoryEntry - so if you go grab the directory entry for each SearchResult - you have full access to everything. But the whole point is that you can define what properties you need, and access those directly on the SearchResult, without having to go back to the underlying DirectoryEntry


The original answer is correct, but if you really need to use the DirectoryEntry and want to access a specific property make sure to load it via RefreshCache before accessing the value:

dirEntry.RefreshCache(new [] { "mail", "displayName" });
var email = (string) dirEntry.Properties["mail"]?.Value;
var displayName = (string) dirEntry.Properties["displayName"]?.Value;

This way only "mail" and "displayName" is loaded from this entry.

More information here

0

精彩评论

暂无评论...
验证码 换一张
取 消