Ian GM
Ian GM

Reputation: 787

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?

Upvotes: 14

Views: 15710

Answers (4)

Ebey Tech
Ebey Tech

Reputation: 112

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

This will get you the full domain\username.

Upvotes: 7

Sergiu Cojocaru
Sergiu Cojocaru

Reputation: 687

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

Upvotes: 21

Lou Watson
Lou Watson

Reputation: 81

You can also pickup the User who launched the app from the Application.OnLaunched method see here.

You still need to declare the User Information capability in you manifest though.

quick example (Ellipses denote non applicable generated code):

sealed partial class App : Application
{
    ... 
    protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        User currentUser = e.User;
        ... 
    }
    ...
}          

Upvotes: 2

marcinax
marcinax

Reputation: 1195

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

Upvotes: 5

Related Questions