2013-04-16 49 views
1

我知道如何從win32_computersystem類獲取全部物理內存。但是以字節或kb爲單位。我想要MB或GB的這些信息。在wmi(wql)查詢中。 wmic也工作。提前致謝。如何通過WMI查詢獲取GB中的總物理內存(RAM)信息?

+1

那麼,你爲什麼不自己轉換它? (如果你正在編碼,在代碼中,否則,使用公式或類似的東西粘貼到Excel中......) – DigCamara

+0

如果你可能正在尋找其他方式來獲得內存大小:http:// www。 commonfixes.com/2014/12/get-systems-physical-ram-using-csharp.html –

回答

5

您必須手動轉換屬性的值。還有更好的使用Win32_PhysicalMemory WMI類。

試試這個樣本

using System; 
using System.Collections.Generic; 
using System.Management; 
using System.Text; 

namespace GetWMI_Info 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 
      try 
      { 
       ManagementScope Scope; 
       Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", "."), null); 

       Scope.Connect(); 
       ObjectQuery Query = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory"); 
       ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query); 
       UInt64 Capacity = 0; 
       foreach (ManagementObject WmiObject in Searcher.Get()) 
       { 
        Capacity+= (UInt64) WmiObject["Capacity"]; 
       } 
       Console.WriteLine(String.Format("Physical Memory {0} gb", Capacity/(1024 * 1024 * 1024))); 
       Console.WriteLine(String.Format("Physical Memory {0} mb", Capacity/(1024 * 1024))); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace)); 
      } 
      Console.WriteLine("Press Enter to exit"); 
      Console.Read(); 
     } 
    } 
} 
5

你可以轉換的Win32_ComputerSystemTotalPhysicalMemory。試試這個:

using System; 
using System.Management; 
namespace WMISample 
{ 
    public class MyWMIQuery 
    { 
     public static void Main() 
     { 
      try 
      { 
       ManagementObjectSearcher searcher = 
        new ManagementObjectSearcher("root\\CIMV2", 
        "SELECT TotalPhysicalMemory FROM Win32_ComputerSystem"); 

       foreach (ManagementObject queryObj in searcher.Get()) 
       { 
        double dblMemory; 
        if(double.TryParse(Convert.ToString(queryObj["TotalPhysicalMemory"]),out dblMemory)) 
        { 
         Console.WriteLine("TotalPhysicalMemory is: {0} MB", Convert.ToInt32(dblMemory/(1024*1024))); 
         Console.WriteLine("TotalPhysicalMemory is: {0} GB", Convert.ToInt32(dblMemory /(1024*1024*1024))); 
        } 
       } 
      } 
      catch (ManagementException e) 
      { 

      } 
     } 
    } 
} 
1

要拍提到,我使用的Win32_PhysicalMemory Capacity屬性,直到我在Windows服務器上遇到不一致的結果,2012年現在我用這兩個屬性(的Win32_ComputerSystem:TotalPhysicalMemory和Win32_PhysicalMemory:容量),並選擇較大他們倆。

+2

歡迎使用堆棧溢出!這真的是一個評論,而不是**原始問題的答案。要批評或要求作者澄清,在他們的帖子下留下評論 - 你總是可以評論你自己的帖子,一旦你有足夠的[聲譽](http://stackoverflow.com/help/whats-reputation),你會能夠[評論任何帖子](http://stackoverflow.com/help/privileges/comment)。 – DavidPostill