[英]Get total installed RAM in C# on Windows 10
我正在制作一个显示一些硬件信息以及其他信息的软件。
我的问题是:
我使用这段代码,在另一个线程中找到的方法: https : //stackoverflow.com/a/15790751/5782981
public ulong InstalledRam { get; set; }
InstalledRam = GetTotalMemoryInBytes();
}
static ulong GetTotalMemoryInBytes()
{
return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}
这返回
8482025472
为了测试它我去
MessageBox.Show(InstalledRam.ToString());
我已经为一些人看到了这项工作,也看到它不适用于 fx。 Windows 7的。
我安装了 8 GB。
我想知道为什么返回值是84...
谢谢!
TotalPhysicalMemory
以字节表示。 如果您希望将内存转换为 GB,请使用以下示例:
Convert.ToInt32(InstalledRam/(1024*1024*1024));
我想我必须做一些计算@easuter。
通过这样做:
var ram = InstalledRam / 1024 / 1024;
MessageBox.Show(ram.ToString());
这给了我 8089,这是我可以使用的值。
谢谢
最好只加载一次计算机信息。 现在在这里使用 Nuget 已经足够快了https://www.nuget.org/packages/OSVersionInfo/
public static class ComputerInformation
{
private static string _WindowsEdition;
private static string _ComputerName;
private static string _Processor;
private static string _RAM;
private static string _Model;
private static void FillPCInfo()
{
ManagementObjectSearcher Search = new ManagementObjectSearcher();
Search.Query = new ObjectQuery("Select * From Win32_ComputerSystem");
foreach (ManagementObject obj in Search.Get())
{
_RAM = $"{Math.Round(Convert.ToDouble(obj["TotalPhysicalMemory"]) / (1024 * 1024 * 1024))} GB";
_Model = obj["Model"]?.ToString();
if (!string.IsNullOrWhiteSpace(_RAM))
break;
}
}
public static string WindowsEdition
{
get
{
if (string.IsNullOrWhiteSpace(_WindowsEdition))
return _WindowsEdition = $"{JCS.OSVersionInfo.Name} {JCS.OSVersionInfo.Edition} {(JCS.OSVersionInfo.OSBits == JCS.OSVersionInfo.SoftwareArchitecture.Bit32 ? "x86" : "x64")} {JCS.OSVersionInfo.ServicePack}".Trim();
return _WindowsEdition;
}
}
public static string ComputerName
{
get
{
if (string.IsNullOrWhiteSpace(_ComputerName))
return _ComputerName = Environment.MachineName;
return _ComputerName;
}
}
public static string Processor
{
get
{
if (string.IsNullOrWhiteSpace(_Processor))
{
ManagementObjectSearcher Search = new ManagementObjectSearcher();
Search.Query = new ObjectQuery("SELECT * FROM Win32_Processor");
var SearchResult = Search.Get();
foreach (ManagementObject obj in SearchResult)
{
_Processor = $"{obj["Name"]} {(SearchResult.Count > 1 ? "(2 processors)" : string.Empty)}".Trim();
if (!string.IsNullOrWhiteSpace(Processor))
break;
}
return _Processor;
}
return _Processor;
}
}
public static string RAM
{
get
{
if (string.IsNullOrWhiteSpace(_RAM))
{
FillPCInfo();
return _RAM;
}
return _RAM;
}
}
public static string Model
{
get
{
if (string.IsNullOrWhiteSpace(_Model))
{
FillPCInfo();
return _Model;
}
return _Model;
}
}
}
然后结果将只在运行时加载一次。 打印列表框中的所有信息:
listBox1.Items.AddRange(new string[] {ComputerInformation.WindowsEdition, ComputerInformation.ComputerName, ComputerInformation.Processor, ComputerInformation.PC.RAM, ComputerInformation.PC.Model});
结果如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.