電腦有許多信息,如名稱、CPU 和硬盤容量等,整理一個 Helper 來獲取,下面目前只整理了一個方法,獲取其它信息的方法相似。git
ComputerInfoHelper.csgithub
using System; using System.Linq; using System.Management; using Wen.Helpers.Common.Computer.Config; namespace Wen.Helpers.Common.Computer { /// <summary> /// 計算機信息助手類 /// </summary> public class ComputerInfoHelper { /// <summary> /// 獲取硬盤容量彙總 /// </summary> public static long GetTotalDiskSize() { try { var diskDriveManagement = new ManagementClass(WmiPath.DiskDrive); var diskDriveManagementInstances = diskDriveManagement.GetInstances(); return diskDriveManagementInstances.OfType<ManagementObject>() .Select(managementObject => Convert.ToInt64(managementObject[ManagementBaseObjectPropertyName.Size])) .Aggregate<long, long>(0, (current, diskSize) => diskSize + current); } catch(Exception e) { Console.WriteLine(e); throw; } } } }
ManagementBaseObjectPropertyName.cside
namespace Wen.Helpers.Common.Computer.Config { public class ManagementBaseObjectPropertyName { /// <summary> /// 名稱 /// </summary> public const string ComputerName = "Name"; /// <summary> /// 顯卡芯片 /// </summary> public const string VideoProcessor = "VideoProcessor"; /// <summary> /// 顯存大小 /// </summary> public const string AdapterRam = "AdapterRAM"; /// <summary> /// 分辨率寬 /// </summary> public const string ScreenWidth = "ScreenWidth"; /// <summary> /// 分辨率高 /// </summary> public const string ScreenHeight = "ScreenHeight"; /// <summary> /// 電腦型號 /// </summary> public const string Version = "Version"; /// <summary> /// 硬盤容量 /// </summary> public const string Size = "Size"; /// <summary> /// 內存容量 /// </summary> public const string Capacity = "Capacity"; /// <summary> /// cpu 核心數 /// </summary> public const string NumberOfCores = "NumberOfCores"; } }
WmiPath.cs測試
namespace Wen.Helpers.Common.Computer.Config { public class WmiPath { /// <summary> /// 內存 /// </summary> public const string PhysicalMemory = "Win32_PhysicalMemory"; /// <summary> /// cpu /// </summary> public const string Processor = "Win32_Processor"; /// <summary> /// 硬盤 /// </summary> public const string DiskDrive = "win32_DiskDrive"; /// <summary> /// 電腦型號 /// </summary> public const string ComputerSystemProduct = "Win32_ComputerSystemProduct"; /// <summary> /// 分辨率 /// </summary> public const string DesktopMonitor = "Win32_DesktopMonitor"; /// <summary> /// 顯卡 /// </summary> public const string VideoController = "Win32_VideoController"; /// <summary> /// 操做系統 /// </summary> public const string OperatingSystem = "Win32_OperatingSystem"; } }
1.電腦硬盤信息spa
2.個人電腦中的硬盤信息操作系統
3.測試代碼3d
4.輸出結果:code
全部硬盤及 U 盤和存儲卡,因生產廠家的計算方式和操做系統的計算方式不同,前者按 1MB = 1000KB 計算,後者按 1MB = 1024KB 計算,因此,實際在電腦中看到的容量會與廠商標稱的容量有必定的差別,其中規律爲 1G = 0.93G (約等於),好比 100G,實際爲 100G * 0.93 = 93G ,具體容量可參考此公式計算。blog
GitHub:https://github.com/liqingwen2015/Wen.Helpers/tree/liqw_home/Wen.Helpers.Common/Computer內存