在.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用户名?
发布评论