How to get real name stored in Active Directory from user name using C #?

I want to create a quick application for people to resolve a username stored in Active Directory from a set of credentials. Some applications provide only a user ID, and there is too much to expect from the end user to activate the Active Directory Users and User Groups snap-in.

The input will be something like "MYCORP \ a_user", and the output will be "Dave Smith" if that is what is stored in AD.

I want this to work in my test domain as well as in a tiered environment.

Can someone provide a sample that does this? Does the search get other attributes from AD, such as phone number, the same pattern?

Target platform: .NET 2.0 and higher.

+3
source share
3 answers

Here is the code I'm using 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, an awkward amount of code is required to do the simplest things. I would like to see a user authentication method that does not require the use of exceptions to control the flow.

+3
source

Working with Active Directory is a bit sick in C #, of course 3.5 adds some new classes, but for pure performance I like to use Powershell and Quest for free. PowerShell commands for Active Directory in this case, the code looks something like this:

get-qaduser userid | select PhoneNumber,DisplayName

, #,

    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);

Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll

+2

See DirectorySearcher by loading the "DisplayName" property.

0
source