![](/img/trans.png)
[英]How to I get the username of the currently logged in user in ASP.NET Core 2, not Application Pool details
[英]How do I get the currently-logged username from a Windows service in .NET?
我有一个需要当前登录的用户名的 Windows 服务。 我尝试了System.Environment.UserName
、Windows 身份和 Windows 表单身份验证,但由于我的服务以系统特权运行,因此所有用户都以用户身份返回“系统”。 有没有办法在不更改我的服务帐户类型的情况下获取当前登录的用户名?
这是用于获取用户名的WMI查询:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
您将需要在 References 下手动添加System.Management
。
如果您在用户网络中,则用户名将不同:
Environment.UserName
将显示格式:'用户名',而不是
System.Security.Principal.WindowsIdentity.GetCurrent().Name
将显示格式:'网络名\\用户名'
选择您想要的格式。
ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem") 解决方案对我来说很好。 但是如果服务是通过远程桌面连接启动的,它就不起作用。 要解决此问题,我们可以询问始终在 PC 上运行的交互式进程的所有者的用户名:explorer.exe。 这样,我们总是从我们的 Windows 服务中获取当前登录的 Windows 用户名:
foreach (System.Management.ManagementObject Process in Processes.Get())
{
if (Process["ExecutablePath"] != null &&
System.IO.Path.GetFileName(Process["ExecutablePath"].ToString()).ToLower() == "explorer.exe" )
{
string[] OwnerInfo = new string[2];
Process.InvokeMethod("GetOwner", (object[])OwnerInfo);
Console.WriteLine(string.Format("Windows Logged-in Interactive UserName={0}", OwnerInfo[0]));
break;
}
}
Tapas答案的修改代码:
Dim searcher As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Dim collection As ManagementObjectCollection = searcher.[Get]()
Dim username As String
For Each oReturn As ManagementObject In collection
username = oReturn("UserName")
Next
以防万一有人正在寻找用户Display Name而不是User Name ,就像我一样。
这是款待:
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName。
在您的项目中添加对System.DirectoryServices.AccountManagement
引用。
你也可以试试
System.Environment.GetEnvironmentVariable("UserName");
试试WindowsIdentity.GetCurrent()
。 您需要添加对System.Security.Principal
引用
完成@xanblax 的回答
private static string getUserName()
{
SelectQuery query = new SelectQuery(@"Select * from Win32_Process");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (System.Management.ManagementObject Process in searcher.Get())
{
if (Process["ExecutablePath"] != null &&
string.Equals(Path.GetFileName(Process["ExecutablePath"].ToString()), "explorer.exe", StringComparison.OrdinalIgnoreCase))
{
string[] OwnerInfo = new string[2];
Process.InvokeMethod("GetOwner", (object[])OwnerInfo);
return OwnerInfo[0];
}
}
}
return "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.