我如何获得当前用户名在。net使用c# ?
当前回答
Use:
System.Security.Principal.WindowsIdentity.GetCurrent().Name
这将是登录名。
其他回答
我完全赞同其他的答案,但我想强调另一个方法,它说
String UserName = Request.LogonUserIdentity.Name;
上述方法返回的用户名格式为:DomainName\ username。例如,EUROPE\UserName
这不同于:
String UserName = Environment.UserName;
显示格式为:UserName
最后:
String UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
它给出:NT AUTHORITY\IUSR(在IIS服务器上运行应用程序时)和DomainName\UserName(在本地服务器上运行应用程序时)。
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
String myUserName = Environment.UserName
这将为您提供输出- your_user_name
获取当前Windows用户名:
using System;
class Sample
{
public static void Main()
{
Console.WriteLine();
// <-- Keep this information secure! -->
Console.WriteLine("UserName: {0}", Environment.UserName);
}
}
如果你在一个用户网络中,那么用户名将是不同的:
Environment.UserName
- Will Display format : 'Username'
而不是
System.Security.Principal.WindowsIdentity.GetCurrent().Name
- Will Display format : 'NetworkName\Username'
选择您想要的格式。
推荐文章
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- MSBuild路径
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- csproj文件中的“Service Include”是干什么用的?
- 如何使用try catch进行异常处理是最佳实践
- 替换字符串中第一次出现的模式
- .NET中字节的字面后缀?
- 如何处理AccessViolationException