我有以下问题: 我想用WMI类获取登录用户。 所以我尝试了这个:
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROMWin32_LoggedOnUser");
foreach (ManagementObject queryObj in searcher.Get())
{
accounttype += queryObj["Antecedent"];
}
}
catch
{
accounttype = "error";
}
但这不起作用,因为queryObj返回对Win32_Account
的引用!
我不知道如何阅读此Win32_Account
引用的值!
顺便说一句,
我知道还有其他方法(比如Environment.UserName
,但我希望大家都能理解这些敬意!
谢谢!
答案 0 :(得分:3)
Win32_LoggedOnUser
WMI类的Antecedent
和Dependent
属性返回WMI Object Path
,这是WMI类实例的唯一ID,您可以访问数据在此类中为ManagementObject
对象创建实例,然后设置从ManagementPath
对象获取的属性Path
。
试试这个样本
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
static void Main(string[] args)
{
try
{
ManagementScope Scope;
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", "localhost"), null);
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_LoggedOnUser");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
//Console.WriteLine("{0,-35} {1,-40}","Antecedent",WmiObject["Antecedent"]);// Reference
//Console.WriteLine("{0,-35} {1,-40}","Dependent",WmiObject["Dependent"]);// Reference
ManagementObject oAntecedent = new ManagementObject();
ManagementPath ObjectPath = new ManagementPath((String)WmiObject["Antecedent"]);//Win32_Account
oAntecedent.Path = ObjectPath;
oAntecedent.Get();
Console.WriteLine("{0,-35} {1,-40}", "Caption", oAntecedent["Caption"]);// String
Console.WriteLine("{0,-35} {1,-40}", "Description", oAntecedent["Description"]);// String
Console.WriteLine("{0,-35} {1,-40}", "Domain", oAntecedent["Domain"]);// String
//Console.WriteLine("{0,-35} {1,-40}", "InstallDate", ManagementDateTimeConverter.ToDateTime((string)WmiObject["InstallDate"]));// Datetime
Console.WriteLine("{0,-35} {1,-40}", "LocalAccount", oAntecedent["LocalAccount"]);// Boolean
Console.WriteLine("{0,-35} {1,-40}", "Name", oAntecedent["Name"]);// String
Console.WriteLine("{0,-35} {1,-40}", "SID", oAntecedent["SID"]);// String
Console.WriteLine("{0,-35} {1,-40}", "SIDType", oAntecedent["SIDType"]);// Uint8
Console.WriteLine("{0,-35} {1,-40}", "Status", oAntecedent["Status"]);// String
Console.WriteLine();
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
}
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
}