我知道如何从win32_computersystem类获取总物理内存。但是以字节或kb为单位。我希望这些信息以MB或GB为单位。在wmi(wql)查询中。 wmic也工作。提前谢谢。
答案 0 :(得分: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();
}
}
}
答案 1 :(得分:6)
您可以转换Win32_ComputerSystem的TotalPhysicalMemory
。试试这个:
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)
{
}
}
}
}
答案 2 :(得分:2)
想要提一下我使用Win32_PhysicalMemory Capacity属性,直到我在Windows Server 2012上遇到不一致的结果。现在我使用两个属性(Win32_ComputerSystem:TotalPhysicalMemory和Win32_PhysicalMemory:Capacity)并选择两者中的较大者。