简体   繁体   English

如何显示当前用户名?

[英]How to show current user's name?

I want to create a textblock that says "Welcome username". 我想创建一个文本框,上面写着“欢迎用户名”。

username = current Windows user. 用户名=当前Windows用户。

I'm working in a WPF project. 我正在WPF项目中工作。

You should use Environment.UserName ( msdn ): 您应该使用Environment.UserNamemsdn ):

Gets the user name of the person who is currently logged on to the Windows operating system. 获取当前登录到Windows操作系统的人员的用户名。

Example: 例:

Console.WriteLine("UserName: {0}", Environment.UserName);

If you want to get the user who is currently running the process, use: 如果要获取当前正在运行该进程的用户,请使用:

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

OR 要么

string userName = System.Environment.UserName

But the user you get from Environment.UserName is not guaranteed to be the user running the current process. 但是,不能保证您从Environment.UserName获得的用户是运行当前进程的用户。

The difference between the two is explained in this comment : 这条评论解释了两者之间的区别:

The reason to prefer WindowsIdentity.GetCurrent() is that this returns the account that the application is running as. 选择WindowsIdentity.GetCurrent()的原因是,它返回应用程序运行所使用的帐户。 This is not necessarily the account that is currently logged into Windows (think "RunAs" or impersonation/delegation). 这不一定是当前登录Windows的帐户(请考虑“ RunAs”或模拟/委派)。 So, if you want to know the logged-in user, use the Environment (if you trust it). 因此,如果您想了解已登录的用户,请使用环境(如果您信任它)。 If you want to know the security context your application is running as, using WindowsIdentity.GetCurrent() . 如果您想使用WindowsIdentity.GetCurrent()来了解应用程序的运行安全上下文。

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

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