Home > OS >  Search AD SchemaClassName using DirectorySearcher
Search AD SchemaClassName using DirectorySearcher

Time:08-11

Following is my implementation to do AD search.

DirectoryEntry de = GetDirectoryEntry();
using (var Search = new DirectorySearcher(de))
{ 
   Search.Filter = "....";
   Search.PropertiesToLoad.Add("Name");
   Search.PropertiesToLoad.Add("distinguishedName");
   Search.PropertiesToLoad.Add("objectGUID");
   var results = Search.FindAll();
   //read properties here...     
   DirectoryEntry  resultde = result.GetDirectoryEntry();
    string schClassName = resultde.SchemaClassName;   //want to add SchemaClassName to PropertiesToLoad



}
 

I have been able to add name,distinguishedName and objectGUID to DirectorySearcher's PropertiesToLoad. I also want to read value of SchemaClassName. Right now I have to call GetDirectoryEntry method to read it. Is it possible to add DirectorySearcher.SchemaClassName to PropertiesToLoad rather than calling GetDirectoryEntry method? Is there any other better option to do the same?

CodePudding user response:

You're looking for the objectClass attribute.

However, that attribute is a multi-value attribute that not only contains the class of the object, but the superclasses. So a user object will contain the values top, person, organizationalPerson, and user.

So if you're looking for the most specific class of the object, look at the last value. For example:

result.Properties["objectClass"][result.Properties["objectClass"].Count - 1]

More reading: Object Class and Object Category

On a side note, make sure to put Search.FindAll() in a using statement. In the Remarks section of the documentation it says:

Due to implementation restrictions, the SearchResultCollection class cannot release all of its unmanaged resources when it is garbage collected. To prevent a memory leak, you must call the Dispose method when the SearchResultCollection object is no longer needed.

So it's more important to dispose of that than to dispose of the DirectorySearcher.

  • Related