gpt4 book ai didi

c# - C#获取用户登录名

转载 作者:太空宇宙 更新时间:2023-11-03 19:24:38 28 4
gpt4 key购买 nike

如何在c#中查询系统登录用户名我用这个方法试过了

static string whoisLoggedIn(string HostOrIP)
{
GUFlag = true;
HostOrIP = Environment.MachineName;
System.Management.ConnectionOptions myConnectionOptions = new System.Management.ConnectionOptions();
myConnectionOptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;

System.Management.ManagementScope objwmiservice;
System.Management.ManagementObjectSearcher myObjectSearcher2;
System.Management.ManagementObjectCollection myCollection2;

try
{
objwmiservice = new System.Management.ManagementScope(("\\\\" + (HostOrIP +
"\\root\\cimv2")), myConnectionOptions);
objwmiservice.Connect();
myObjectSearcher2 = new System.Management.ManagementObjectSearcher(objwmiservice.Path.ToString(),
"Select UserName from Win32_ComputerSystem");
myObjectSearcher2.Options.Timeout = new TimeSpan(0, 0, 0, 0, 7000);
myCollection2 = myObjectSearcher2.Get();
GUFlag = false;

foreach (System.Management.ManagementObject myObject in myCollection2)
{
if (!(myObject.GetPropertyValue("Username") == null))
{
string Userx = myObject.GetPropertyValue("Username").ToString();
int posx = Userx.LastIndexOf("\\");
if ((posx > 0))
{
Userx = Userx.Substring((posx + 1));
return Userx.ToUpper();
}
}
}
return "<Nobody>";
}
catch (Exception)
{
return "<Nobody>";
}
finally {

GUFlag = false;
}

}

但问题是在 myObjectSearcher2.Get(); 上发生了一些时间死锁有没有办法获取登录用户名

最佳答案

你试过吗?

Environment.UserName

它会给你当前登录windows的用户名

编辑

我在这里找到了这段代码 http://www.debugging.com/bug/20243 ,它可能会解决您的问题。

使用 WMI ( http://msdn.microsoft.com/en-us/library/system.management.aspx ) 的解决方案:

    private string GetUserName()
{
string result = "";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName, Name FROM Win32_ComputerSystem"))
{
foreach (ManagementObject mo in searcher.Get())
{
if (mo["UserName"] != null)
result = mo["UserName"].ToString();
if (mo["Name"] != null)
result += " (" + mo["Name"].ToString() + ")";
}
}
return result;
}

关于c# - C#获取用户登录名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9719609/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com