How I can get my first name last name with c# in my system (logging in windows with Active Directory username and pass)?
Is it possible to do that without going to t
The problem with the approved answer is that if you have a policy of Lastname, Firstname in place, then DisplayName gives Smith, John, not John Smith. There are two ways to get the correct form, the userPrincipal.Name property contains "John Smith (jsmith1)" so you could use this, and just string.Split on "(". Or use the following:
private string ConvertUserNameToDisplayName(string currentSentencedByUsername)
{
string name = "";
using (var context = new PrincipalContext(ContextType.Domain))
{
var usr = UserPrincipal.FindByIdentity(context, currentSentencedByUsername);
if (usr != null)
name = usr.GivenName+" "+usr.Surname;
}
if (name == "")
throw new Exception("The UserId is not present in Active Directory");
return name;
}
This would give the required form "John Smith" as required by the original poster.