在C#中确定操作系统和处理器类型

Ben*_*307 11 .net c# wmi operating-system

我想检查一下我使用的操作系统类型和处理器类型.这应该在运行时检查.我试过用

System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")
Run Code Online (Sandbox Code Playgroud)

System.OperatingSystem osInfo2 = System.Environment.OSVersion;
Console.WriteLine(osInfo2.ToString());
Run Code Online (Sandbox Code Playgroud)

但这只是VS正在运行的环境.
有人告诉我使用WMI检查它,但我不知道如何.有人可以帮助我吗?

tre*_*tey 30

检索操作系统信息:

var wmi =
    new ManagementObjectSearcher( "select * from Win32_OperatingSystem" )
    .Get()
    .Cast<ManagementObject>()
    .First();

OS.Name = ((string)wmi["Caption"]).Trim();
OS.Version = (string)wmi["Version"];
OS.MaxProcessCount = (uint)wmi["MaxNumberOfProcesses"];
OS.MaxProcessRAM = (ulong)wmi["MaxProcessMemorySize"];
OS.Architecture = (string)wmi["OSArchitecture"];
OS.SerialNumber = (string)wmi["SerialNumber"];
OS.Build = ((string)wmi["BuildNumber"]).ToUint();
Run Code Online (Sandbox Code Playgroud)

检索CPU信息:

var cpu =
    new ManagementObjectSearcher( "select * from Win32_Processor" )
    .Get()
    .Cast<ManagementObject>()
    .First();

CPU.ID = (string)cpu["ProcessorId"];
CPU.Socket = (string)cpu["SocketDesignation"];
CPU.Name = (string)cpu["Name"];
CPU.Description = (string)cpu["Caption"];
CPU.AddressWidth = (ushort)cpu["AddressWidth"];
CPU.DataWidth = (ushort)cpu["DataWidth"];
CPU.Architecture = (CPU.CpuArchitecture)(ushort)cpu["Architecture"];
CPU.SpeedMHz = (uint)cpu["MaxClockSpeed"];
CPU.BusSpeedMHz = (uint)cpu["ExtClock"];
CPU.L2Cache = (uint)cpu["L2CacheSize"] * (ulong)1024;
CPU.L3Cache = (uint)cpu["L3CacheSize"] * (ulong)1024;
CPU.Cores = (uint)cpu["NumberOfCores"];
CPU.Threads = (uint)cpu["NumberOfLogicalProcessors"];

CPU.Name =
   CPU.Name
   .Replace( "(TM)", "™" )
   .Replace( "(tm)", "™" )
   .Replace( "(R)", "®" )
   .Replace( "(r)", "®" )
   .Replace( "(C)", "©" )
   .Replace( "(c)", "©" )
   .Replace( "    ", " " )
   .Replace( "  ", " " );
Run Code Online (Sandbox Code Playgroud)


小智 5

是的WMI是执行此类操作的最佳方式您可以使用它来检索操作系统信息:

ManagementObjectSearcher objMOS = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM  Win32_OperatingSystem");
Run Code Online (Sandbox Code Playgroud)