1

I'm trying to add a feature in my C# app that looks up the email address associated with the Windows login, but I can not find anything on this!

The closest thing I found was it being listed in the Registry @ "HKEY_CURRENT_USER\Software\Microsoft\IdentityCRL" for one person, but not on any of my machines.

I've also tried "System.DirectoryServices.AccountManagement.UserPrincipal.Current.EmailAddress" but it returns nothing.

Has anyone ever had to look this up programmatically before? If so, any advice?

Fire Starter
  • 53
  • 1
  • 8
  • Note that you don't need an MS account to use Windows, so this is not always possible. But perhaps [System.Security.Principal.WindowsIdentity.GetCurrent()](https://stackoverflow.com/a/1240379/3034273) has some interesting info. – Xerillio Apr 02 '21 at 20:28
  • Unfortunately, that only returns the DOMAIN\USERNAME – Fire Starter Apr 02 '21 at 22:04

1 Answers1

1

Interesting question. It got me looking around. This is what I got so far from a C# WinApp project. Under a Microsoft login account, I got it to display the "UserName" property that had my associated email address. Under a regular local account, it returned nothing. Run with it. Good luck.

using System;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Forms;

namespace WindowsAuthenticationProbing
{
    class Program
    {
        static void Main(string[] args)
        {
            //interesting to look at, but does not reveal the associated Windows login email
            var myIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
            
            var userTask = Windows.System.User.FindAllAsync().AsTask();
            
            userTask.Wait();

            var users = userTask.Result;

            foreach (var user in  users)
            {
                var propTask = user.GetPropertiesAsync(new[] { "UserName" }).AsTask();
                
                propTask.Wait();
                
                var props = propTask.Result;

                foreach(var x in props)
                {
                    MessageBox.Show($"User is {x.Value}");
                }
            }            
        }

  
    }

}
Rex Henderson
  • 412
  • 2
  • 7
  • fyi, I used Task.Wait because the GetPRopertiesAsync threw an "method call unexpected at this time" exception. Wait on the task to finish avoided the issue. – Rex Henderson Apr 02 '21 at 22:35
  • Thanks for the help, but I get this error: "The name 'Windows' does not exist in the current context" on Windows.System.User.FindAllAsync().AsTask() – Fire Starter Apr 03 '21 at 01:14
  • Using Visual Studio, start a new net core 3.1 project , output type of Windows Application. Install nuget packages Microsoft.Identity.Client.Desktop and (optionally) System.Security.Principal.Windows for the one var myIdentity code line, or get rid of that code line. – Rex Henderson Apr 03 '21 at 02:37