獲取電腦內部信息 - ComputerInfoHelper 一、代碼 ComputerInfoHelper.cs ManagementBaseObjectPropertyName.cs WmiPath.cs 二、測試 1.電腦硬碟信息 2.我的電腦中的硬碟信息 3.測試代碼 4.輸出結果: 所有硬 ...
獲取電腦內部信息 - ComputerInfoHelper
一、代碼
ComputerInfoHelper.cs
/// <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.cs
namespace Wen.Helpers.Common.Computer.Config { public class ManagementBaseObjectPropertyName { /// <summary> /// 名稱 /// </summary> public const string Name = "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.電腦硬碟信息
2.我的電腦中的硬碟信息
3.測試代碼
4.輸出結果:
所有硬碟及 U 盤和存儲卡,因生產廠家的計算方式和操作系統的計算方式不一樣,前者按 1MB = 1000KB 計算,後者按 1MB = 1024KB 計算,所以,實際在電腦中看到的容量會與廠商標稱的容量有一定的差異,其中規律為 1G = 0.93G (約等於),比如 100G,實際為 100G * 0.93 = 93G ,具體容量可參考此公式計算。