简体   繁体   English

在Windows 10 C#UWP通用Windows应用程序中获取UserName

[英]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. 我正在努力解决Windows 10 UWP世界中的另一项简单任务。

I simply need the UserName of the current Windows user. 我只需要当前Windows用户的UserName。 Environment.UserName is just not a thing in UWP. Environment.UserName在UWP中不是一个东西。 And no amount of searching the web has helped so far. 到目前为止,搜索网络的数量都没有帮助。 Hence my post here. 因此我的帖子在这里。

Anyone? 任何人? Is this just not possible now? 这现在不可能吗?

  1. Add "User Account Information" capability to your app in the Package.appxmanifest 在Package.appxmanifest中为您的应用添加“用户帐户信息”功能

Package.appxmanifest,用户帐户信息

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

As I can see, there is a User class available (UWP): https://msdn.microsoft.com/en-us/library/windows/apps/windows.system.user.aspx 我可以看到,有一个User类可用(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);

You can also pickup the User who launched the app from the Application.OnLaunched method see here . 您还可以从Application.OnLaunched方法中获取启动应用程序的用户,请参阅此处

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;
        ... 
    }
    ...
}          
// get username
public string UserNameStr { get; set; } = WindowsIdentity.GetCurrent().Name;

This will get you the full domain\\username. 这将为您提供完整的域\\用户名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM