Get UserName in a Windows 10 C# UWP Universal Windows app
- Add "User Account Information" capability to your app in the Package.appxmanifest
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);