Ian GM Ian GM - 28 days ago 8
C# Question

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

I am struggling with yet another simple task in the Windows 10 UWP world.

I simply need the UserName of the current Windows user. Environment.UserName is just not a thing in UWP. And no amount of searching the web has helped so far. Hence my post here.

Anyone? Is this just not possible now?

Thanks.

Answer

1

  1. Add "User Account Information" capability to your app
  2. 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;
    }