Search code examples
windows-store-appswindows-10

Username with System.User


Today I wanted to greet the user in my app by name, but I did not manage to get it.

I found System.User, but lacking some examples I did not manage to get the info I needed. I saw no possibility to get the current user (id) to call User.GetFromId().

Can you guide me into the right direction? Have I been on the wrong path?


Solution

  • Okay, So first things first, getting access to a user's personal information is a privilege you have to request, so in your store app's Package.appxmanifest, you'll need to enable the User Account Information capability in the Capabilities tab.

    Next, you'll want to be using the Windows.System.User class, not the System.User (System.User isn't available to Windows store apps, which you appear to be discussing given the tags you provided for your question)

    Third, you'll want to request personal information like this.

    IReadOnlyList<User> users = await User.FindAllAsync(UserType.LocalUser, UserAuthenticationStatus.LocallyAuthenticated);
    User user = users.FirstOrDefault();
    if (user != null)
    {
       String[] desiredProperties = new String[]
       {
          KnownUserProperties.FirstName,
          KnownUserProperties.LastName,
          KnownUserProperties.ProviderName,
          KnownUserProperties.AccountName,
          KnownUserProperties.GuestHost,
          KnownUserProperties.PrincipalName,
          KnownUserProperties.DomainName,
          KnownUserProperties.SessionInitiationProtocolUri,
       };
    
       IPropertySet values = await user.GetPropertiesAsync(desiredProperties);
       foreach (String property in desiredProperties)
       {
          string result;
          result = property + ": " + values[property] + "\n";
          System.Diagnostics.Debug.WriteLine(result);
       }
    }
    

    When you call GetPropertiesAsync, your user will get a permission prompt from the system asking them if they want to give you access to that. If they answer 'No', you'll get an empty user object (but you'll still get a unique token you can use to distinguish that user if they use the app again).

    If they answer yes, you'll be able to get access to the properties below, and various others.

    See the UserInfo Sample Microsoft provided for more examples.