我尝试在 c# 中获取当前登录用户的名称 - 而不是我可以在 Environment.UserName 中轻松找到的帐户名称。我想像资源管理器那样枚举 MyComputer 上的文件夹。我该怎么做,或者有其他方法可以获取用户的正确名称吗?
提前致谢。
我尝试在 c# 中获取当前登录用户的名称 - 而不是我可以在 Environment.UserName 中轻松找到的帐户名称。我想像资源管理器那样枚举 MyComputer 上的文件夹。我该怎么做,或者有其他方法可以获取用户的正确名称吗?
提前致谢。
尝试使用:
System.Security.Principal.WindowsIdentity.GetCurrent().Name
这应该返回当前登录用户的帐户及其姓名。
如果在用户名更改后这不起作用,另一种方法是获取当前用户的 SID,然后查找与该 SID 匹配的用户名。
using System.Security.Principal;
string sid = WindowsIdentity.GetCurrent().Owner.ToString();
return new SecurityIdentifier(sid).Translate(typeof(NTAccount)).ToString();
如果失败,请获取 SID 并尝试通过 WMI 或通过注册表找到匹配的用户。有关如何手动执行此操作的说明在这里: http: //pcsupport.about.com/od/registry/ht/find-user-security-identifier.htm
如果您可以手动确认这些方法中的任何一个返回新用户名,那么只需在代码中使用 WMI 调用或注册表访问来实现它。
用它 ,
string windowLoging = WindowsIdentity.GetCurrent().Name;
或者
string windowsLogin = Page.User.Identity.Name;
或者
string windowsLogin = Environment.GetEnvironmentVariable("USERNAME");
@damienc88 您的链接将我引向解决方案:
SelectQuery query = new SelectQuery("Win32_UserAccount", string.Format("Domain='{0}'", Environment.MachineName));
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject mObject in searcher.Get())
{
Console.WriteLine((string)mObject["Name"] + "\t" + (string)mObject["FullName"]);
}
“FullName”是我搜索过的属性。非常感谢。——哈拉尔德·皮特罗