views:

249

answers:

4

I have the following code that loads a user's Active Directory DirectoryEntry object from the user's SID:

public static DirectoryEntry GetUserDirectoryEntry(SecurityIdentifier sid)
{
    return new DirectoryEntry(string.Format("LDAP://<SID={0}>", sid.Value));
}

Is there a more efficient way to do this? I'm having to optimize my code because of performance issues, and I need to squeeze down to the absolute fastest code that I can. It doesn't necessarily have to load from an SID. I just need to know the most efficient way to get the users DirectoryEntry.

EDIT: I'm restricted to using .Net 2.0.

+1  A: 

You should try defining more filters and specifying user as the type in your criteria.

Eran Betzalel
I'm not doing a search. Are you saying it would be more efficient to use a directory searcher class?
Max Schmeling
By search I meant you are using LDAP query (searching the AD). Every LDAP query you run, count as a search.
Eran Betzalel
+2  A: 

Directory operations are fairly slow regardless of the means you use to access objects in the directory. Without more context it is difficult to recommend a more efficient approach, but in general, have you considered grabbing sets of users at once, multithreading, and caching to design around the issue?

Also, I cannot say which is more efficient, but have you tried the new System.DirectoryServices.AccountManagement namespace in .NET 3.5? If anyone should have optimized this, it would be Microsoft, but I think we have all been let down before.

Jerry Bullard
I edited the question to add that I'm restricted to using .Net 2.0. Also, I only need to pull one user at a time.
Max Schmeling
+1  A: 

I don't think it makes a big difference how you load your DirectoryEntry - whether by SID or by fully-qualified DN - it just takes a set amount of time for the AD bind operation to work

That bind actually doesn't happen when you instantiate your DirectoryEntry - it's delayed until you start using properties on your DirectoryEntry, or access the .NativeObject property.

So no matter which way you do it - creating your DirectoryEntry based on some uniquely identifying value will just take its time.

Marc

marc_s
+1  A: 

What about the System.DirectoryServices.Protocols namespace. It doesn't have the overhead of using ADSI and ought to be a lot faster. It looks a bit unwieldy at the start but once you get used to it, it's no so bad. Plus you can do proper asynchronous searches.

Have a look at:

serialhobbyist