.net 获取当前电脑的总内存大小:
private int SysPhisicalMemory()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象
searcher.Query = new SelectQuery("Win32_PhysicalMemory ", "", new string[] { "Capacity" });//设置查询条件
ManagementObjectCollection collection = searcher.Get(); //获取内存容量
ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator();
long capacity = 0;
while (em.MoveNext())
{
ManagementBaseObject baseObj = em.Current;
if (baseObj.Properties["Capacity"].Value != null)
{
try
{
capacity += long.Parse(baseObj.Properties["Capacity"].Value.ToString());
}
catch { return 0; }
}
}
return (int)(capacity / 1024 / 1024);
}
获取当前电脑的内存条,内存型号,内存大小等情况
/// <summary>
/// 获取内存信息
/// </summary>
/// <returns></returns>
public static string GetPhysicalMemory()
{
ManagementScope oMs = new ManagementScope();
ObjectQuery oQuery = new ObjectQuery("SELECT * FROM Win32_PhysicalMemory");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
ManagementObjectCollection oCollection = oSearcher.Get();
StringBuilder sb = new StringBuilder();
uint i = 1;
foreach (ManagementObject obj in oCollection)
{
var indexSize = Convert.ToInt64(obj.GetPropertyValue("Capacity"));
var m = obj.GetPropertyValue("Manufacturer");
var c = obj.GetPropertyValue("Caption");
object s;
try
{
// 时钟频率属性在虚拟机测试环境下可能无法获取
s = obj.GetPropertyValue("ConfiguredClockSpeed") + "MHz";
}
catch (Exception) { s = "频率未知"; }
sb.AppendLine($"序号{i}>>{indexSize / 1024 / 1024 / 1024}GB,{s},{m},{c}");
i++;
}
return sb.ToString();
}
以下是运行效果: