获取Windows用户名-不同的方法 [英] Get Windows user name - different methods
问题描述
在.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屋!