I have a function that retrieves the fullname of a user based on user name and domain. This function runs in ASP.NET thread under an impersonated user. When I use Directory searcher on a remote AD branch, I believe I’m getting the SID number instead of the property (cannot verify it occurs on a different box).
public string GetUserFullName(string userName, string domainName) { DirectoryEntry rootEntry = new DirectoryEntry('GC://dc=company,dc=net'); string filter = string.Format('(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(userPrincipalName={0}@{1}.company.net))', userName, domainName); DirectorySearcher searcher = new DirectorySearcher(rootEntry, filter, new string[] { 'displayName' }); rootEntry.AuthenticationType = AuthenticationTypes.Secure; searcher.PageSize = 1000; searcher.ServerTimeLimit = new TimeSpan(0, 10, 0); searcher.ReferralChasing = ReferralChasingOption.All; searcher.Asynchronous = false; SearchResult result = searcher.FindOne(); if (result != null) { return (string) result.Properties['displayName'][0]; } else { throw new Exception('Active Directory could not resolve your user name'); } }
What version of the .NET framework are you working against? The AD stuff has been revamped quite extensively in .NET 3.5, and offers strongly typed constructs for User and groups and stuff like that now.
Check out the excellent article ‘Managing Directory Security Principals in the .NET Framework 3.5‘ by my buddies Joe Kaplan and Ethan Wilansky on MSDN. Excellent stuff indeed.
First of all, you get a class called UserPrincipal which is strongly typed, e.g. all the basic properties are properties on your object. Very helpful indeed.
Secondly, you get a nice ‘query-by-example’ method using PrincipalSearcher – check out this sample from Joe and Ethan’s article:
If there’s any chance at all, try to get to .NET 3.5 for your AD stuff !
Marc