prog1011
prog1011

Reputation: 3495

Read ActiveDirectorySchema using C#

I am trying to read Active Directory schema data using DirectorySearcher, like this:

DirectoryEntry entry = new DirectoryEntry("LDAP://********/CN=Schema,*****");

var filter = "(&(objectCategory=attributeSchema))";
var directorySearcher = new DirectorySearcher(entry, filter);

var searchResult = directorySearcher.FindAll();
DirectoryEntry schemaTest2 = entry.SchemaEntry;

// error on this line: 
// "The directory cannot report the number of properties."
foreach (var prop in schemaTest2.Properties.PropertyNames) 
{
    string propName = prop.ToString();                    
}

Does anyone have an idea why this error happens? Or do you have any suggestion how to read AD schema using DirectorySerarcher?

Note: I can not use

ActiveDirectorySchema schema = ActiveDirectorySchema.GetCurrentSchema();

as I am facing some other issue with that.

Any suggestion would be highly appreciated !

Thanks.

Upvotes: 1

Views: 834

Answers (1)

Zwan
Zwan

Reputation: 642

I got the same error here. The solution from Microsoft is below:

DirectoryEntry  myDirectoryEntry=new DirectoryEntry();
// Display the 'SchemaClassName'.
Console.WriteLine("Schema class name:" + myDirectoryEntry.SchemaClassName);

// Gets the SchemaEntry of the ADS object.
DirectoryEntry mySchemaEntry = myDirectoryEntry.SchemaEntry;

if (string.Compare(mySchemaEntry.Name, "container") == 0)
{
   foreach(DirectoryEntry myChildDirectoryEntry in myDirectoryEntry.Children)
      Console.WriteLine(myChildDirectoryEntry.Path);
}

In my case the container does not work myDirectoryEntry.SchemaClassName = domainDNS and to get some results I needed to modify the code into:

DirectoryEntry myDirectoryEntry = new DirectoryEntry();

    // Display the 'SchemaClassName'.
    Console.WriteLine("Schema class name:" + myDirectoryEntry.SchemaClassName);

    // Gets the SchemaEntry of the ADS object.
    DirectoryEntry mySchemaEntry = myDirectoryEntry.SchemaEntry;

    if (string.Compare(mySchemaEntry.Name, "domainDNS") == 0)
    {
        foreach (DirectoryEntry myChildDirectoryEntry in myDirectoryEntry.Children)
            Console.WriteLine(myChildDirectoryEntry.Path);
    }
    Console.ReadLine();

I hope it helps you.

Upvotes: 1

Related Questions