最好只加载一次计算机信息。现在在这里使用 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;
}
}
}
然后结果将仅在运行时加载一次。打印 ListBox 中的所有信息:
listBox1.Items.AddRange(new string[] {ComputerInformation.WindowsEdition, ComputerInformation.ComputerName, ComputerInformation.Processor, ComputerInformation.PC.RAM, ComputerInformation.PC.Model});
结果为:
- Windows 7 旗舰版 x64 服务包1
- 联想-PC
- 4 GB 内存
- 联想T430