天道酬勤

博观而约取,厚积而薄发!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

用C#获取系统内存(转载)

Posted on 2010-04-29 15:49  Happy Coding  阅读(612)  评论(0编辑  收藏  举报

原文地址: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;
        }    
    }
}