how to get domain user info from AD in C#
3097 ワード
First, we have to know the user connection name (here from an ASP.NET page).
Then we have to define some stuff : search filter including object type and connection name, domain, properties to retrieve from Active Directory.
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.
Finally, once information is retrieved in the DirectoryEntry object, we can get the details of each property defined.
http://www.pin5i.com/showtopic-21054.html
string principal = this.Context.User.Identity.Name;
Then we have to define some stuff :
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 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