I have Windows 10/11 endpoints being a part of Azure AD domain. The local DC (hybrid mode) is disabled. I need to find out the userPrincipalName programmatically for every session/logged-in user.
Running whoami.exe /upn in the command line gives me proper UPN, like user.user@domain.com.
But the .NET code
string upn = System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName;`
fails with:
System.InvalidCastException: Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'. at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue) at System.DirectoryServices.AccountManagement.UserPrincipal.get_Current()
Is there any way to gigure out how whoami utility does the job? I cannot run any command liners from my code.