Get username in a Windows 10 C # UWP Universal Windows application

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

I just need the username of the current Windows user. Environment.UserName is simply not something in UWP. And no Internet search has yet succeeded. Hence my post.

Is anyone Is it really impossible now?

+11
c # windows uwp
source share
4 answers
  • Add "User Account Information" for your application in Package.appxmanifest

Package.appxmanifest, User Account Information

  1. Use this code to get your 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; } 
+17
source share

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

Try the following:

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

You can also select the user who launched the application from Application.OnLaunched , see here .

You still need to declare the possibility of user information in your manifest.

Quick example (Ellipses indicate inapplicable generated code):

 sealed partial class App : Application { ... protected override void OnLaunched(LaunchActivatedEventArgs e) { User currentUser = e.User; ... } ... } 
+1
source share
 // get username public string UserNameStr { get; set; } = WindowsIdentity.GetCurrent().Name; 

This will give you the full domain \ username.

0
source share

All Articles