用C#獲取系統(tǒng)內(nèi)存

2010-08-28 10:46:13來源:西部e網(wǎng)作者:

打開visual studio.net 2003,依次點(diǎn)擊文件--新建--項(xiàng)目--控制臺(tái)應(yīng)用程序,語言選C#,在程序里增加以下方法,然后在main()函數(shù)里加入
System.Console.WriteLine("系統(tǒng)內(nèi)存是:"+GetPhisicalMemory().ToString());
--------------------------------------------------------
private int GetPhisicalMemory()
{    
            
ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用于查詢一些如系統(tǒng)信息的管理對(duì)象
searcher.Query = new SelectQuery("Win32_PhysicalMemory","",new string[]{"Capacity"});//設(shè)置查詢條件
ManagementObjectCollection collection = searcher.Get(); //獲取內(nèi)存容量
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("有錯(cuò)誤發(fā)生!請(qǐng)聯(lián)系軟件作者!\n","錯(cuò)誤信息",MessageBoxButtons.OK,MessageBoxIcon.Error,MessageBoxDefaultButton.Button1);
return 0;
        }
    }
}
return capacity;}   
關(guān)鍵詞:C#

贊助商鏈接: