wmi查询返回空

时间:2014-01-12 19:23:09

标签: c# wmi

var ram = new ManagementObjectSearcher("select MaxCapacity from Win32_PhysicalMemoryArray").Get().Cast<ManagementObject>().First();;
RamAmount = (uint)ram["MaxCapacity"] / 4096;

我得到了这段代码来获得安装RAM的总数。但是查询返回空,我得到错误“序列包含无元素”这基本上意味着查询为空。 任何人都知道为什么因为这个程序在2000个其他PC上运行并且工作正常。

1 个答案:

答案 0 :(得分:0)

我不确定你是如何得到这个错误的,因为ManagementObjectSearcher class没有提供索引器,所以你的代码甚至都不会编译。您需要调用Get method来检索结果:

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select MaxCapacity from Win32_PhysicalMemoryArray"))
using (ManagementObjectCollection results = searcher.Get())
{
    uint ramKilobytes = results
        .Cast<ManagementBaseObject>()
        .Sum(memoryArray => (uint) memoryArray["MaxCapacity"]);

    RamAmount = ramKilobytes / 4096;
}