获取计算机内部信息 - ComputerInfoHelper
电脑有许多信息,如名称、CPU 和硬盘容量等,整理一个 Helper 来获取,下面目前只整理了一个方法,获取其它信息的方法类似。
一、代码
ComputerInfoHelper.cs
using System;using System.Linq;using System.Management;using Wen.Helpers.Common.Computer.Config;namespace Wen.Helpers.Common.Computer{ ////// 计算机信息助手类 /// public class ComputerInfoHelper { ////// 获取硬盘容量汇总 /// public static long GetTotalDiskSize() { try { var diskDriveManagement = new ManagementClass(WmiPath.DiskDrive); var diskDriveManagementInstances = diskDriveManagement.GetInstances(); return diskDriveManagementInstances.OfType() .Select(managementObject => Convert.ToInt64(managementObject[ManagementBaseObjectPropertyName.Size])) .Aggregate (0, (current, diskSize) => diskSize + current); } catch(Exception e) { Console.WriteLine(e); throw; } } }}
ManagementBaseObjectPropertyName.cs
namespace Wen.Helpers.Common.Computer.Config{ public class ManagementBaseObjectPropertyName { ////// 名称 /// public const string ComputerName = "Name"; ////// 显卡芯片 /// public const string VideoProcessor = "VideoProcessor"; ////// 显存大小 /// public const string AdapterRam = "AdapterRAM"; ////// 分辨率宽 /// public const string ScreenWidth = "ScreenWidth"; ////// 分辨率高 /// public const string ScreenHeight = "ScreenHeight"; ////// 电脑型号 /// public const string Version = "Version"; ////// 硬盘容量 /// public const string Size = "Size"; ////// 内存容量 /// public const string Capacity = "Capacity"; ////// cpu 核心数 /// public const string NumberOfCores = "NumberOfCores"; }}
WmiPath.cs
namespace Wen.Helpers.Common.Computer.Config{ public class WmiPath { ////// 内存 /// public const string PhysicalMemory = "Win32_PhysicalMemory"; ////// cpu /// public const string Processor = "Win32_Processor"; ////// 硬盘 /// public const string DiskDrive = "win32_DiskDrive"; ////// 电脑型号 /// public const string ComputerSystemProduct = "Win32_ComputerSystemProduct"; ////// 分辨率 /// public const string DesktopMonitor = "Win32_DesktopMonitor"; ////// 显卡 /// public const string VideoController = "Win32_VideoController"; ////// 操作系统 /// public const string OperatingSystem = "Win32_OperatingSystem"; }}
二、测试
1.电脑硬盘信息
2.我的电脑中的硬盘信息
3.测试代码
4.输出结果:
所有硬盘及 U 盘和存储卡,因生产厂家的计算方式和操作系统的计算方式不一样,前者按 1MB = 1000KB 计算,后者按 1MB = 1024KB 计算,所以,实际在电脑中看到的容量会与厂商标称的容量有一定的差异,其中规律为 1G = 0.93G (约等于),比如 100G,实际为 100G * 0.93 = 93G ,具体容量可参考此公式计算。
GitHub: