how to get domain user info from AD in C#

First, we have to know the user connection name (here from an ASP.NET page).

string principal = this.Context.User.Identity.Name;

Then we have to define some stuff :

  • search filter including object type and connection name,
  • domain,
  • properties to retrieve from Active Directory.
string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", principal);
string domain = "DOMAIN";
string[] properties = new string[] { "fullname" };

To search in Active Directory, we need the following objects :

  • DirectoryEntry : represents a node or object in the Active Directory hierarchy,
  • DirectorySearcher : performs queries against Active Directory Domain Services.
DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure);
DirectorySearcher searcher = new DirectorySearcher(adRoot);
searcher.SearchScope = SearchScope.Subtree;
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.PropertiesToLoad.AddRange(properties);
searcher.Filter = filter;
 
SearchResult result = searcher.FindOne();
DirectoryEntry directoryEntry = result.GetDirectoryEntry();

Finally, once information is retrieved in the DirectoryEntry object, we can get the details of each property defined.

string displayName = directoryEntry.Properties["displayName"][0].ToString();
string firstName = directoryEntry.Properties["givenName"][0].ToString();
string lastName = directoryEntry.Properties["sn"][0].ToString();
string email = directoryEntry.Properties["mail"][0].ToString();
 
from: http://weblogs.asp.net/jpinquie/archive/2008/02/06/how-to-get-domain-user-information-from-active-directory-in-c.aspx
 

关于优化.NET访问Active Directory的性能,参考

http://www.pin5i.com/showtopic-21054.html

原文地址:https://www.cnblogs.com/flyinthesky/p/1670574.html