要使用C#讀取WMI的ManagementObject集合,您可以按照以下步驟進(jìn)行操作:
using System.Management;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject obj in collection)
{
// 訪問對象的屬性
string name = obj["Name"].ToString();
string size = obj["Size"].ToString();
// ...
}
完整的示例代碼如下所示:
using System;
using System.Management;
namespace WmiExample
{
class Program
{
static void Main(string[] args)
{
try
{
// 創(chuàng)建一個ManagementObjectSearcher對象并設(shè)置查詢條件
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
// 執(zhí)行查詢并獲取結(jié)果集
ManagementObjectCollection collection = searcher.Get();
// 遍歷結(jié)果集并訪問每個ManagementObject對象的屬性
foreach (ManagementObject obj in collection)
{
string name = obj["Name"].ToString();
string size = obj["Size"].ToString();
Console.WriteLine($"驅(qū)動器名稱:{name},大小:{size}");
}
}
catch (Exception e)
{
Console.WriteLine($"發(fā)生錯誤:{e.Message}");
}
Console.ReadLine();
}
}
}
此示例將查詢所有的磁盤驅(qū)動器并打印出其名稱和大小。您可以根據(jù)您的需求修改查詢條件和訪問的屬性。