简体   繁体   中英

C# Active Directory Browsing best practices

Straight to the point, I have a request for a new project on which I have to find the primary and secondary owners for a specific list of Active Directory groups. When I get the array of secondary owners for each group, each of the owners are identified by their "distinguishedName" which led me to use a snippet like this to get the owner's info:

using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + distinguishedName))
{
        using (DirectorySearcher dSearch = new DirectorySearcher(entry))
        {
            SearchResult found = dSearch.FindOne();
            if (found != null)
            {
                using (DirectoryEntry userEntry = found.GetDirectoryEntry())
                {
                    Console.WriteLine("Username: " + userEntry.Properties["namefield"].Value + " : " + userEntry.Properties["emailfield"].Value);
                }
            }
            else
            {
                Console.WriteLine("User not found with distinguishedName: " + distinguishedName);
            }
        }
}
GC.Collect();

I am a little concerned by the performance of this task since I have to get this information at the page loading sequence to check if the logged user is an owner or not. I have other AD browsing task to do and I've been doing some research on best practices with C# and AD and haven't found anything helpful yet so I though that you guys could provide some input on this.

Thanks for all your help.

f you have distinguished name of an object, you can bind to the object directly. Searching with DirectorySearcher is an excessive operation. Just create DirectoryEntry object and call its RefreshCache method. The fastest performance in ad is provided by classes located under System.DirectoryServices.Protocols namespace. Also one more optimization can be done: at the start of your program create a DirectoryEntry object and bind, eg To rootdse. This will establish ldap connection under the hood. All other queries will use this ldap connection. Keep the object alive until the program finishes

Credit to: oldovets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM