用C#获取系统内存

来源:互联网 发布:java读取xlsx文件 编辑:程序博客网 时间:2024/05/21 11:36
用C#获取系统内存
===========================================================
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;
        }    
    }