Getting the Full Name of the Current User
One of the developers in our team recently encountered a problem of getting the display name of the current user.
The .NET framework exposes the user name through Environment.UserName
or System.Security.Principal.WindowsIdentity.GetCurrent().Name
but there’s no API to get the user’s display name.
The simplest implementation to get the display name would be using DirectoryServices:
public static string GetUserFullName(string domain, string userName) {
DirectoryEntry userEntry = new DirectoryEntry("WinNT://" + domain + "/" + userName + ",User");
return (string)userEntry.Properties["fullname"].Value;
}
The above method can be called with the current user name and domain to get the user’s fullname:
GetUserFullName(Environment.UserDomainName, Environment.UserName)
This method will fail to provide a correct result of the fullname property is not configured in ActiveDirectory.
Windows provide an unmanaged API called GetUserNameEx that can be called using interop:
/// <summary>
/// Wraps the GetUserNameEx API in secur32.dll
/// </summary> /// <see>
/// https://msdn2.microsoft.com/en-us/library/ms724435.aspx
/// </see>
public static class GetUserNameExUtil {
#region Interop Definitions
public enum EXTENDED_NAME_FORMAT {
NameUnknown = 0,
NameFullyQualifiedDN = 1,
NameSamCompatible = 2,
NameDisplay = 3,
NameUniqueId = 6,
NameCanonical = 7,
NameUserPrincipal = 8,
NameCanonicalEx = 9,
NameServicePrincipal = 10,
NameDnsDomain = 12,
}
[System.Runtime.InteropServices.DllImport("secur32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetUserNameEx(int nameFormat, StringBuilder userName, ref int userNameSize);
#endregion
public static string GetUserName(EXTENDED_NAME_FORMAT nameFormat) {
if (Environment.OSVersion.Platform != PlatformID.Win32NT) {
return null;
}
StringBuilder userName = new StringBuilder(1024);
int userNameSize = userName.Capacity;
if (GetUserNameEx((int) nameFormat, userName, ref userNameSize) != 0) {
string[] nameParts = userName.ToString().Split('\\');
return nameParts[0];
}
return null;
}
public static string GetUserFullName() {
return GetUserName(EXTENDED_NAME_FORMAT.NameDisplay);
}
}
Just call GetUserNameExUtil.GetUserDisplayName()
to get the user’s display name…