I’m trying to get the name of the currently logged in Windows user in the format “John Doe”. I’m not sure if there’s an accepted term for this, but think, the name you see when you bring up the start menu, as opposed to the string you write to sign in.
I started with looking through the answers on this question, but they seem to be entirely concerned with finding the user’s login name. At first I considered a work-around like this:
string GetName(string userName) => string.Join(' ', Regex.Split(userName, @"[A-Z]"));
string name = GetName(Environment.UserName);
But realised that this isn’t really a good one-size-fits-all solution, as usernames that are not in the format ^[A-Z]([^A-Z]*)[A-Z]([^A-Z]*)$
would format wrongly or not at all.
GetName("doejohn") // "doejohn"
GetName("RonaldMcDonald") // "Ronald Mc Donald"
My next stop was here to see if I could find how to get the value from the system directly instead of computing it myself, and I got a decent bit further: System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
seemed to be exactly what I want in theory, and while this may or may not work in other scenarios, it doesn’t seem to work in mine due to being part of a group.
var name1 = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // "AzureADJohnDoe"
var name2 = UserPrincipal.Current.DisplayName;
// System.Exception:
// Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal'
// to type 'System.DirectoryServices.AccountManagement.UserPrincipal'.
My best idea now, though I’ve hit a wall, is using GroupPrincipal
if UserPrincipal
fails, but I’m open to other solutions if that’s wrong or against best practice.
2