2013-04-16 51 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