Skip to main content

Posts

Showing posts from 2019

Getting user First Name and Last Name from Active Directory

Recently, I had to create a asp.net MVC portal for organizing test messages. Since site is personalized for User, we were required to fetch and disply username, when they login. This being intranet site, user is authenticated using Windows Authentication. Windows user names are most of the time are mix of literal, not conveying users First and Last name. I used following code to get User First and Last name, using DirectorySearcher class to query Active Directory. Since user name in HttpContext is in format DomainName\\UserName, I had to extract user name alone and use it filter.


using System.DirectoryServices; ... ... DirectorySearcher ds = new DirectorySearcher(); var indexOfBS = User.Identity.Name.IndexOf("\\"); ds.Filter = String.Format("((SAMAccountName={0}))", User.Identity.Name.Substring(indexOfBS + 1, User.Identity.Name.Length - indexOfBS - 1)); ds.PropertiesToLoad.Add("givenName"); ds.PropertiesToLoad.Add("sn"); var directoryEntry = ds.…