用C#获取系统内存

2010-08-28 10:46:13来源:西部e网作者:

打开visual studio.net 2003,依次点击文件--新建--项目--控制台应用程序,语言选C#,在程序里增加以下方法,然后在main()函数里加入
System.Console.WriteLine("系统内存是:"+GetPhisicalMemory().ToString());
--------------------------------------------------------
private 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
        {
                        MessageBox.Show("有错误发生!请联系软件作者!\n","错误信息",MessageBoxButtons.OK,MessageBoxIcon.Error,MessageBoxDefaultButton.Button1);
return 0;
        }
    }
}
return capacity;}   
关键词:C#

赞助商链接: