Get UPN for logged on Azure AD user with C#

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();
}

5 reasons to continue remote work after Covid-19

1. Interacting and contributing remotely Ongoing remote working in the workplace provides opportunities to improve communication and share ideas. This allows you to interact...
Erik
1 min read

Leave a Reply

Your email address will not be published.