如何使用不同的方法获取Windows用户名? [英] How to get Windows user name using different methods?

查看:63
本文介绍了如何使用不同的方法获取Windows用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中,似乎有几种方法可以获取当前的Windows用户名.其中三个是:

In .NET, there appears to be several ways to get the current Windows user name. Three of which are:

string name = WindowsIdentity.GetCurrent().Name;

string name = Thread.CurrentPrincipal.Identity.Name;

string name = Environment.UserName;

有什么区别,为什么选择一种方法而不是另一种方法?还有其他方法吗?

What's the difference, and why choose one method over the other? Are there any other ways?

推荐答案

Environment.UserName调用advapi32.dll中的GetUserName.这意味着,如果您要冒充其他用户,则此属性将反映出来.

Environment.UserName calls GetUserName within advapi32.dll. This means that if you're impersonating another user, this property will reflect that.

Thread.CurrentPrincipal有一个setter,可以通过编程方式进行更改.(顺便说一下,这不是假冒.)

Thread.CurrentPrincipal has a setter and can be changed programmatically. (This is not impersonation btw.)

WindowsIdentity是您当前的 windows 身份(如果有).它不一定反映用户,认为带有FormsAuthentication的ASP.NET.然后WindowsIdentity将成为NT服务,而FormsIdentity将成为登录用户.还有一个PassportIdentity,您可以构建自己的东西来进一步使事情复杂化.

WindowsIdentity is your current windows identity, if any. It will not necessarily reflect the user, think ASP.NET with FormsAuthentication. Then the WindowsIdentity will be the NT-service, but the FormsIdentity will be the logged in user. There's also a PassportIdentity, and you can build your own stuff to complicate things further.

这篇关于如何使用不同的方法获取Windows用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆