Get UserName in a Windows 10 C# UWP Universal Windows app

  1. Add "User Account Information" capability to your app in the Package.appxmanifest

Package.appxmanifest, User Account Information

  1. Use this code to get user display name:

    private async void Page_Loaded(object sender, RoutedEventArgs e)
    {
        IReadOnlyList<User> users = await User.FindAllAsync();
    
        var current = users.Where(p => p.AuthenticationStatus == UserAuthenticationStatus.LocallyAuthenticated && 
                                    p.Type == UserType.LocalUser).FirstOrDefault();
    
        // user may have username
        var data = await current.GetPropertyAsync(KnownUserProperties.AccountName);
        string displayName = (string)data;
    
        //or may be authinticated using hotmail 
        if(String.IsNullOrEmpty(displayName))
        {
    
            string a = (string)await current.GetPropertyAsync(KnownUserProperties.FirstName);
            string b = (string)await current.GetPropertyAsync(KnownUserProperties.LastName);
            displayName = string.Format("{0} {1}", a, b);
        }
    
        text1.Text = displayName;
    }
    

// get username
public string UserNameStr { get; set; } = WindowsIdentity.GetCurrent().Name;

This will get you the full domain\username.


As I can see, there is a User class available (UWP): https://msdn.microsoft.com/en-us/library/windows/apps/windows.system.user.aspx

Try this:

var users = await User.FindAllAsync(UserType.LocalUser);
var name = await users.FirstOrDefault().GetPropertyAsync(KnownUserProperties.AccountName);

Tags:

Windows

C#

Uwp