2013-12-08 89 views
1

我有以下問題: 我想用WMI類獲取登錄用戶。 所以,我想這一點: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參考的值!

BTW, 我知道還有其他方法(如Environment.UserName,但我想大致瞭解這些reverences!

謝謝!

回答

3

Win32_LoggedOnUser WMI類的AntecedentDependent性質返回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(); 
     } 
    } 
}