鉴于 WMI仅适用于Windows ,并且Linux和Mac等操作系统没有注册表,如何获取.NET Core中的处理器名称?
我打算使以下方法(使用注册表)跨平台:
private static string GetProcessorName()
{
var key = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0\");
return key?.GetValue("ProcessorNameString").ToString() ?? "Not Found";
}
Run Code Online (Sandbox Code Playgroud)
您可以假设我可以在运行时知道我正在运行什么操作系统。
在 Linux 上,我使用了此链接中的示例中的 FreeCSharp 类如何在 Mono 下获取可用的虚拟和物理内存大小?创建一个可以读取 cpuinfo 的类。对于 .net core,您很可能必须从 nuget 获取 System.Text.RegularExpressions。我还没有在 .net core only mono 下进行测试,但我很确定它应该可以工作。
using System;
using System.Text.RegularExpressions;
using System.IO;
namespace Example.Lib.Common
{
/// <summary>
/// Reads /proc/cpuinfo to obtain common values
/// </summary>
public class LinuxCpuInfo
{
public string VendorId { get; private set; }
public int CpuFamily { get; private set; }
public int Model { get; private set; }
public string ModelName { get; private set; }
public int Stepping { get; private set; }
public double MHz { get; private set; }
public string CacheSize { get; private set; }
public void GetValues()
{
string[] cpuInfoLines = File.ReadAllLines(@"/proc/cpuinfo");
CpuInfoMatch[] cpuInfoMatches =
{
new CpuInfoMatch(@"^vendor_id\s+:\s+(.+)", value => VendorId = Conversion.ObjectToString(value)),
new CpuInfoMatch(@"^cpu family\s+:\s+(.+)", value => CpuFamily = Conversion.ObjectToInt(value)),
new CpuInfoMatch(@"^model\s+:\s+(.+)", value => Model = Conversion.ObjectToInt(value)),
new CpuInfoMatch(@"^model name\s+:\s+(.+)", value => ModelName = Conversion.ObjectToString(value)),
new CpuInfoMatch(@"^stepping\s+:\s+(.+)", value => Stepping = Conversion.ObjectToInt(value)),
new CpuInfoMatch(@"^cpu MHz\s+:\s+(.+)", value => MHz = Conversion.ObjectToDouble(value)),
new CpuInfoMatch(@"^cache size\s+:\s+(.+)", value => CacheSize = Conversion.ObjectToString(value))
};
foreach (string cpuInfoLine in cpuInfoLines)
{
foreach (CpuInfoMatch cpuInfoMatch in cpuInfoMatches)
{
Match match = cpuInfoMatch.regex.Match(cpuInfoLine);
if (match.Groups[0].Success)
{
string value = match.Groups[1].Value;
cpuInfoMatch.updateValue(value);
}
}
}
}
public class CpuInfoMatch
{
public Regex regex;
public Action<string> updateValue;
public CpuInfoMatch(string pattern, Action<string> update)
{
this.regex = new Regex(pattern, RegexOptions.Compiled);
this.updateValue = update;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8487 次 |
| 最近记录: |