Brian Lyttle
Brian Lyttle

Reputation: 14579

How do I get a real name stored in Active Directory from an username with C#?

I want to create a quick application for people to resolve the name of a user stored in Active Directory from a set of credentials. Some applications only provide the user id and it is too much to expect an end user to fire up the Active Directory Users and Groups MMC snap-in.

Input would be something like "MYCORP\a_user" and output would be "Dave Smith" if that is what is stored in AD.

I want this to be able to run in my test domain and also in a multi-forest environment.

Can someone provide a sample that does this? Does retrieval of other attributes from AD such as telephone number follow the same pattern?

Target platform: .NET 2.0 and above.

Upvotes: 3

Views: 2399

Answers (3)

Adam Lassek
Adam Lassek

Reputation: 35505

Here's the code I use, taken from my authentication class:

string[] strUserName = username.Split("\\".ToCharArray());
using (var entry = new DirectoryEntry("LDAP://" + ADServer, ADServiceDomain + "\\" + ADServiceAccount, ADServicePassword))
using (var ds = new DirectorySearcher(entry, "sAMAccountName=" + strUserName[1])) {
  ds.SearchScope = SearchScope.Subtree;
  SearchResult result = ds.FindOne();
  string fullname = result.Properties["displayName"][0].ToString();
}

System.DirectoryServices sucks. As you can see, it takes a ridiculous amount of code to do even the most basic things. I'd like to see a user authentication method that didn't require using exceptions for flow control.

Upvotes: 3

Scott Weinstein
Scott Weinstein

Reputation: 19117

Working with Active Directory is a bit painfull in C#, sure 3.5 adds some new classes to help, but for pure productivity I like to use Powershell and Quest's free PowerShell Commands for Active Directory in which case the code looks something like

get-qaduser userid | select PhoneNumber,DisplayName

if you need this to run as part of your C# program, you can do that too

    public static IEnumerable<PSObject> Invoke(string script, params object[] input)
    {
        IList errors = null;
        using (var run = new RunspaceInvoke())
        {
            var psResults = run.Invoke(script, input, out errors);
            if (errors != null && errors.Count > 0)
                Debug.WriteLine(errors.Count);
            foreach (PSObject res in psResults)
                yield return res;
        }
    }
    PSObject psUser = POSHelp.Invoke(
        @"add-pssnapin Quest.ActiveRoles.ADManagement
        ($userid) = $input | % { $_ }
        get-qaduser $userid", "auserid").Single();
     Debug.WriteLine(psUser.Properties["DisplayName"].Value);

add a ref to Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll

Upvotes: 2

sfuqua
sfuqua

Reputation: 5853

See DirectorySearcher, loading the property "DisplayName".

Upvotes: 0

Related Questions