我如何获得当前用户名在。net使用c# ?
当前回答
使用实际登录用户的System.Windows.Forms.SystemInformation.UserName作为环境。UserName仍然返回当前进程正在使用的帐户。
其他回答
如果你在一个用户网络中,那么用户名将是不同的:
Environment.UserName
- Will Display format : 'Username'
而不是
System.Security.Principal.WindowsIdentity.GetCurrent().Name
- Will Display format : 'NetworkName\Username'
选择您想要的格式。
你可能还想尝试使用:
Environment.UserName;
像这样…:
string j = "Your WindowsXP Account Name is: " + Environment.UserName;
希望这对你有所帮助。
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
对于要分发给几个用户的Windows窗体应用程序,其中许多用户通过vpn登录,我尝试了几种方法,这些方法都适用于我的本地机器测试,但不适用于其他机器。我偶然发现了一篇微软的文章,我对它进行了改编,而且效果很好。
using System;
using System.Security.Principal;
namespace ManageExclusion
{
public static class UserIdentity
{
// concept borrowed from
// https://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity(v=vs.110).aspx
public static string GetUser()
{
IntPtr accountToken = WindowsIdentity.GetCurrent().Token;
WindowsIdentity windowsIdentity = new WindowsIdentity(accountToken);
return windowsIdentity.Name;
}
}
}
环境文档。UserName似乎有点矛盾:
环境。用户名属性
在同一页上写着:
获取当前登录到Windows操作系统的用户的用户名。
AND
显示启动当前线程的用户名
如果您测试环境。UserName使用RunAs,它会给你RunAs用户帐户名,而不是最初登录Windows的用户。
推荐文章
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- MSBuild路径
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- csproj文件中的“Service Include”是干什么用的?
- 如何使用try catch进行异常处理是最佳实践
- 替换字符串中第一次出现的模式
- .NET中字节的字面后缀?
- 如何处理AccessViolationException