This is how you get the User Principal Name (UPN) for the currently logged on Azure AD user on a Windows machine.
It works both in offline and online scenarios.
public static string GetCurrentUserUpn()
{
Process whoamiProcess = new Process();
whoamiProcess.StartInfo.FileName = "whoami.exe";
whoamiProcess.StartInfo.Arguments = "/upn";
whoamiProcess.StartInfo.UseShellExecute = false;
whoamiProcess.StartInfo.RedirectStandardOutput = true;
whoamiProcess.StartInfo.RedirectStandardError = true;
whoamiProcess.Start();
var output = whoamiProcess.StandardOutput.ReadToEnd().Trim();
var error = whoamiProcess.StandardError.ReadToEnd().Trim();
whoamiProcess.WaitForExit();
var regex = new Regex(@"^(?!\.)[a-zA-Z0-9_.+-]{1,63}[^.]@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+){1,}$");
if (regex.IsMatch(output))
return output;
else
throw new Exception(error ?? "Could not get UPN");
}
static void Main(string[] args)
{
try
{
var upn = GetCurrentUserUpn();
if (upn != null)
Console.WriteLine($"UPN: {upn}");
}
catch(Exception ex)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"Error: {ex.Message}");
Console.ResetColor();
}
Console.ReadKey();
}