原文地址:http://www.cnblogs.com/yohen/articles/833285.html
using System;
using System.Management; //此命名空间需要在
//“解决方案资源管理里右键点击”引用“,添加引用,在弹出的
//对话框中找到System.Management
namespace ConsoleApplication1
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("正在计算系统内存容量,请稍候.....");
Console.WriteLine("实际内存容量为:"+GetPhisicalMemory().ToString());
Console.ReadLine();
}
private static int GetPhisicalMemory()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象
searcher.Query = new SelectQuery("Win32_PhysicalMemory","",new string[]{"Capacity"});//设置查询条件
ManagementObjectCollection collection = searcher.Get(); //获取内存容量
ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator();
int capacity = 0;
while(em.MoveNext())
{
ManagementBaseObject baseObj = em.Current;
if(baseObj.Properties["Capacity"].Value != null)
{
try
{
capacity += int.Parse(baseObj.Properties["Capacity"].Value.ToString());
}
catch
{
Console.WriteLine("有错误发生!","错误信息");
return 0;
}
}
}
return capacity;
}
}
}