1

我知道如何从 win32_computersystem 类中获取总物理内存。但这以字节或 kb 为单位。我想要此信息以 MB 或 GB 为单位。在 wmi (wql) 查询中。wmic 也可以。提前致谢。

4

3 回答 3

6

您可以转换TotalPhysicalMemoryWin32_ComputerSystem 。尝试这个 :

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)
            {

            }
        }
    }
}
于 2013-04-17T07:13:28.383 回答
6

您必须手动转换属性的值。也最好使用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();
        }
    }
}
于 2013-04-16T18:34:49.497 回答
2

想提一下,我使用了 Win32_PhysicalMemory Capacity 属性,直到在 Windows Server 2012 上遇到不一致的结果。现在我使用这两个属性(Win32_ComputerSystem:TotalPhysicalMemory 和 Win32_PhysicalMemory:Capacity)并选择两者中较大的一个。

于 2015-03-18T12:06:16.713 回答