I need to get the display name of the current user and cannot find a solution that always works. Just for clarity, I'm not looking for a username. I need John Dow. The value displayed in the Start menu.
There are many posts about this issue, however no one has solved my problem.
Get Windows username
How to get the display name AD of the current user during login
These two posts lead me to:
PrincipalContext context = domain.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase) ? new PrincipalContext(ContextType.Machine) : new PrincipalContext(ContextType.Domain, domain); UserPrincipal userPrincipal = new UserPrincipal(context) { SamAccountName = username }; PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal); userPrincipal = searcher.FindOne() as UserPrincipal; string displayName = userPrincipal.DisplayName;
And this code works for the most part. However, if the user has disabled / stopped the server service on his computer, I get an exception: "Server service is not running."
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
The same mistakes.
How to get the full username at login?
StringBuilder name = new StringBuilder(1024); uint userNameSize = (uint)name.Capacity; const int NameDisplay = 3; GetUserNameEx(NameDisplay, name, ref userNameSize)
Returns an error, but an empty string if the user is not in the domain.
How do you read the username (first and last) on all versions of Windows?
// get SAM compatible name <server/machine>\\<username> if (0 != GetUserNameEx(2, username, ref userNameSize)) { IntPtr bufPtr; try { string domain = Regex.Replace(username.ToString(), @"(.+)\\.+", @"$1"); DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain); DomainController dc = DomainController.FindOne(context); if (0 == NetUserGetInfo(dc.IPAddress, Regex.Replace(username.ToString(), @".+\\(.+)", "$1"), 10, out bufPtr)) { var userInfo = (USER_INFO_10) Marshal.PtrToStructure(bufPtr, typeof (USER_INFO_10)); return Regex.Replace(userInfo.usri10_full_name, @"(\S+), (\S+)", "$2 $1"); } } finally { NetApiBufferFree(out bufPtr); } }
With the above, I get an ActiveDirectoryObjectNotFoundException with the message "Domain controller not found in the domain .." when I call DomainController.FindOne.
I did not find the registry setting for the display name.
I do not know what else to try. Please help.