您的位置:首页 > 编程语言 > C#

关于c# 中读取系统内存大小的问题。

2014-03-06 12:44 429 查看
在程序中,调用WMI的时候,出现一个问题,就是我系统有插了两条内存条,共4G。然而自己只能在程序中查到安装内存为2G,感觉有点不淡定。这是之前的代码。

static ManagementObjectSearcher PhysicalMemory = new ManagementObjectSearcher("select * from Win32_PhysicalMemory");

// 安装内存
string hd = strInstalledMemory + String.Format("{0} GB", Convert.ToInt64(GetValue(PhysicalMemory, "Capacity")) / 1024 / 1024 / 1024);

static object GetValue(ManagementObjectSearcher searcher, string propName)

{
foreach (ManagementObject mobj in searcher.Get())
return mobj[propName];
throw new NotSupportedException();
}

这个明显是不完整的,并没有查询到所有的内存,多个内存条的话,就不行了。然后我改进了下:

//获取安装内存大小

double capacity = 0;
string hd = "";
ManagementClass cimobject1 = new ManagementClass("Win32_PhysicalMemory");
ManagementObjectCollection moc1 = cimobject1.GetInstances();
foreach (ManagementObject mo1 in moc1)
{
capacity += ((Math.Round(Int64.Parse(mo1.Properties["Capacity"].Value.ToString()) / 1024 / 1024 / 1024.0, 1)));

}
moc1.Dispose();
cimobject1.Dispose();

hd = "安装内存:"+ capacity + "G";

这样就搞定了。水平有限,如有更好的方法,求分享。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: