.net 直接获取当前电脑运行登录的账号名
var username=Environment.UserName
获取当前操作系统有那些账号信息,账号描述,密码能否更改,是否被禁用,所在域(组织)为等信息
需要使用 root\\CIMV2 ,查询 Win32_UserAccount 信息获取.
/// <summary>
/// 获取账户名
/// </summary>
/// <returns></returns>
public static string GetAccountName()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_UserAccount");
StringBuilder stringBuilder = new StringBuilder();
foreach (ManagementObject wmi in searcher.Get())
{
try
{
var n = wmi.GetPropertyValue("Name")?.ToString();
var la = (bool)wmi.GetPropertyValue("LocalAccount") ? "本地账户" : "非本地账户";
var des = wmi.GetPropertyValue("Description")?.ToString().TrimEnd('。').TrimEnd('.');
des = string.IsNullOrEmpty(des) ? "无描述" : des;
var dis = (bool)wmi.GetPropertyValue("Disabled") ? "被禁用" : "未禁用";
var pa = (bool)wmi.GetPropertyValue("PasswordChangeable") ? "可改密码" : "不可更改密码";
var dom = wmi.GetPropertyValue("Domain")?.ToString();
stringBuilder.AppendLine($"{n}>>{la},{des},{pa},{dis},所在域(组织)为{dom}");
stringBuilder.AppendLine();
}
catch { }
}
return stringBuilder.ToString();
}