I have the following problem:
I want to get the the logged in user with a WMI class.
So I tried this:
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROMWin32_LoggedOnUser");
foreach (ManagementObject queryObj in searcher.Get())
{
accounttype += queryObj["Antecedent"];
}
}
catch
{
accounttype = "error";
}
But this don't work because the queryObj returns a reference to Win32_Account
!
I have no Idea how I can read the values of this Win32_Account
reference!
BTW,
I know there are other ways ( like Environment.UserName
, but I want to generally understand these reverences!
Thanks!
The Antecedent
and Dependent
properties of the Win32_LoggedOnUser
WMI class returns a WMI Object Path
, which is a unique id for a WMI class instance, you can access the data of to this class creating a instance to the ManagementObject
object and then setting the property Path
obtained from a ManagementPath
object.
Try this sample
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();
}
}
}