others - C#在Windows 10 UWP通用Windows应用程序中获取用户名

75 0

我只需要获取当前Windows用户的UserName。Environment.UserName在UWP中没啥用,

现在不可能做到吗?

时间: 原作者:

117 1
  • 在Package.appxmanifest中将"User Account Information"添加到应用程序中

Package.appxmanifest, User Account Information

使用此代码获取用户名:


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;


}



原作者:
126 2

有一个User类可用(UWP ): https://msdn.microsoft.com/en-us/library/windows/apps/windows.system.user.aspx

尝试这个:


var users = await User.FindAllAsync(UserType.LocalUser);


var name = await users.FirstOrDefault().GetPropertyAsync(KnownUserProperties.AccountName);



原作者:
115 2

你还可以从Application.OnLaunched方法中获取启动该应用程序的用户,请参见这个

你仍然需要在清单中声明用户信息功能。


sealed partial class App : Application


{


 ... 


 protected override void OnLaunched(LaunchActivatedEventArgs e)


 {


 User currentUser = e.User;


 ... 


 }


 ...


} 



原作者:
71 0

// get username


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



这将获得完整的域名用户名。

原作者:
...