简体   繁体   中英

Search LastName and FirstName in AD

I want to retrieve the first name and last name of the user that is logged in his/her machine using AD. I use the following code:

string server = ConfigurationManager.AppSettings["ActiveDirectory.Server"];

DirectoryEntry entry = new DirectoryEntry(@"LDAP://" + server);
DirectorySearcher searcher = new DirectorySearcher(entry);

User user = GetUser(entry);

searcher.Filter = "sAMAccountName=" + user.UserAD;
searcher.PropertiesToLoad.Add("memberof");
SearchResult result = searcher.FindOne();

private static User GetUser(DirectoryEntry userEntry)
{
    Usuario user = new User();
    string[] username = HttpContext.Current.Request.ServerVariables["AUTH_USER"].Split('\\');

    //THIS IS WHAT I NEED BUT IT DOES RETURN null.
    //User.Name= (string)userEntry.Properties["givenName"].Value;
    //User.LastName= (string)userEntry.Properties["sn"].Value;

    user.Domain = username[0];
    user.UserAD = username[1];

    return user;
}

Now, I know searcher.PropertiesToLoad have a [memberof] and [adspath] , the last one gives me the first and last name separated with a comma, something like CN="gates, billy" but I dont want to use substrings and index, is there any property like [firstName] , [lastName] in the list properties?

I did search that DirectoryEntry have a property called givenName and sn but this returns null

The PropertiesToLoad set is exactly what you need to modify. Active Directory will return only the properties which are defined in this set, that's why you don't see givenName and sn . Just add these properties as well:

searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("sn");

Alternatively, just add the property * to load all of them:

searcher.PropertiesToLoad.Add("*");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM