Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 611
Brian Lyttle Avatar asked Jan 25 '26 02:01

Brian Lyttle


1 Answers

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.

like image 67
Adam Lassek Avatar answered Jan 27 '26 16:01

Adam Lassek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!