【C#】獲取電腦CPU、內存、屏幕、磁盤等信息

通過WMI類來獲取電腦各種信息,參考文章:WMI_04_常見的WMI類的屬性_wmi scsilogicalunit_fantongl的博客-CSDN博客

自己整理了獲取電腦CPU、內存、屏幕、磁盤等信息的代碼

 #region 系統信息/// <summary>/// 電腦信息/// </summary>public partial class ComputerInfo{/// <summary>/// 系統版本/// <para>示例:Windows 10 Enterprise</para>/// </summary>public static string OSProductName { get; } = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", 0);/// <summary>/// 操作系統版本/// <para>示例:Microsoft Windows 10.0.18363</para>/// </summary>public static string OSDescription { get; } = System.Runtime.InteropServices.RuntimeInformation.OSDescription;/// <summary>/// 操作系統架構(<see cref="Architecture">)/// <para>示例:X64</para>/// </summary>public static string OSArchitecture { get; } = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString();/// <summary>/// 獲取系統信息/// </summary>/// <returns></returns>public static SystemInfo GetSystemInfo(){SystemInfo systemInfo = new SystemInfo();var osProductName = OSProductName.Trim().Replace(" ", "_");var osVersionNames = Enum.GetNames(typeof(OSVersion)).ToList();for (int i = 0; i < osVersionNames.Count; i++){var osVersionName = osVersionNames[i];if (osProductName.Contains(osVersionName)){systemInfo.OSVersion = (OSVersion)Enum.Parse(typeof(OSVersion), osVersionName);systemInfo.WindowsVersion = osProductName.Replace(osVersionName, "").Replace("_", " ");}}systemInfo.WindowsVersionNo = OSDescription;systemInfo.Architecture = OSArchitecture;return systemInfo;}}/// <summary>/// 系統信息/// </summary>public class SystemInfo{/// <summary>/// 系統版本。如:Windows 10/// </summary>public string WindowsVersion { get; set; }/// <summary>/// 系統版本。如:專業版/// </summary>public OSVersion OSVersion { get; set; }/// <summary>/// Windows版本號。如:Microsoft Windows 10.0.18363/// </summary>public string WindowsVersionNo { get; set; }/// <summary>/// 操作系統架構。如:X64/// </summary>public string Architecture { get; set; }}/// <summary>/// 系統客戶版本/// </summary>public enum OSVersion{/// <summary>/// 家庭版/// </summary>Home,/// <summary>/// 專業版,以家庭版為基礎/// </summary>Pro,Professional,/// <summary>/// 企業版,以專業版為基礎/// </summary>Enterprise,/// <summary>/// 教育版,以企業版為基礎/// </summary>Education,/// <summary>/// 移動版/// </summary>Mobile,/// <summary>/// 企業移動版,以移動版為基礎/// </summary>Mobile_Enterprise,/// <summary>/// 物聯網版/// </summary>IoT_Core,/// <summary>/// 專業工作站版,以專業版為基礎/// </summary>Pro_for_Workstations}#endregion#region CPU信息public partial class ComputerInfo{/// <summary>/// CPU信息/// </summary>/// <returns></returns>public static CPUInfo GetCPUInfo(){var cpuInfo = new CPUInfo();var cpuInfoType = cpuInfo.GetType();var cpuInfoFields = cpuInfoType.GetProperties().ToList();var moc = new ManagementClass("Win32_Processor").GetInstances();foreach (var mo in moc){foreach (var item in mo.Properties){if (cpuInfoFields.Exists(f => f.Name == item.Name)){var p = cpuInfoType.GetProperty(item.Name);p.SetValue(cpuInfo, item.Value);}}}return cpuInfo;}}/// <summary>/// CPU信息/// </summary>public class CPUInfo{/// <summary>/// 操作系統類型,32或64/// </summary>public uint AddressWidth { get; set; }/// <summary>/// 處理器的名稱。如:Intel(R) Core(TM) i3-8100 CPU @ 3.60GHz/// </summary>public string Name { get; set; }/// <summary>/// 處理器的當前實例的數目。如:4。4核/// </summary>public uint NumberOfEnabledCore { get; set; }/// <summary>/// 用于處理器的當前實例邏輯處理器的數量。如:4。4線程/// </summary>public uint NumberOfLogicalProcessors { get; set; }/// <summary>/// 系統的名稱。計算機名稱。如:GREAMBWANG/// </summary>public string SystemName { get; set; }}#endregion#region 內存信息public partial class ComputerInfo{/// <summary>/// 內存信息/// </summary>/// <returns></returns>public static RAMInfo GetRAMInfo(){var ramInfo = new RAMInfo();var totalPhysicalMemory = TotalPhysicalMemory;var memoryAvailable = MemoryAvailable;var conversionValue = 1024.0 * 1024.0 * 1024.0;ramInfo.TotalPhysicalMemoryGBytes = Math.Round((double)(totalPhysicalMemory / conversionValue), 1);ramInfo.MemoryAvailableGBytes = Math.Round((double)(memoryAvailable / conversionValue), 1);ramInfo.UsedMemoryGBytes = Math.Round((double)((totalPhysicalMemory - memoryAvailable) / conversionValue), 1);ramInfo.UsedMemoryRatio = (int)(((totalPhysicalMemory - memoryAvailable) * 100.0) / totalPhysicalMemory);return ramInfo;}/// <summary>/// 總物理內存(B)/// </summary>/// <returns></returns>public static long TotalPhysicalMemory{get{long totalPhysicalMemory = 0;ManagementClass mc = new ManagementClass("Win32_ComputerSystem");ManagementObjectCollection moc = mc.GetInstances();foreach (ManagementObject mo in moc){if (mo["TotalPhysicalMemory"] != null){totalPhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());}}return totalPhysicalMemory;}}/// <summary>/// 獲取可用內存(B)/// </summary>public static long MemoryAvailable{get{long availablebytes = 0;ManagementClass mos = new ManagementClass("Win32_OperatingSystem");foreach (ManagementObject mo in mos.GetInstances()){if (mo["FreePhysicalMemory"] != null){availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());}}return availablebytes;}}}/// <summary>/// 內存信息/// </summary>public class RAMInfo{/// <summary>/// 總物理內存(GB)/// </summary>public double TotalPhysicalMemoryGBytes { get; set; }/// <summary>/// 獲取可用內存(GB)/// </summary>public double MemoryAvailableGBytes { get; set; }/// <summary>/// 獲取已用內存(GB)/// </summary>public double UsedMemoryGBytes { get; set; }/// <summary>/// 內存使用率/// </summary>public int UsedMemoryRatio { get; set; }}#endregion#region 屏幕信息public partial class ComputerInfo{/// <summary>/// 屏幕信息/// </summary>public static GPUInfo GetGPUInfo(){GPUInfo gPUInfo = new GPUInfo();gPUInfo.CurrentResolution = MonitorHelper.GetResolution();gPUInfo.MaxScreenResolution = GetGPUInfo2();return gPUInfo;}/// <summary>/// 獲取最大分辨率/// </summary>/// <returns></returns>private static Size GetMaximumScreenSizePrimary(){var scope = new System.Management.ManagementScope();var q = new System.Management.ObjectQuery("SELECT * FROM CIM_VideoControllerResolution");UInt32 maxHResolution = 0;UInt32 maxVResolution = 0;using (var searcher = new System.Management.ManagementObjectSearcher(scope, q)){var results = searcher.Get();foreach (var item in results){if ((UInt32)item["HorizontalResolution"] > maxHResolution)maxHResolution = (UInt32)item["HorizontalResolution"];if ((UInt32)item["VerticalResolution"] > maxVResolution)maxVResolution = (UInt32)item["VerticalResolution"];}}return new Size((int)maxHResolution, (int)maxVResolution);}/// <summary>/// 獲取最大分辨率2/// CurrentHorizontalResolution:1920/// CurrentVerticalResolution:1080/// </summary>/// <returns></returns>public static Size GetGPUInfo2(){var gpu = new StringBuilder();var moc = new ManagementObjectSearcher("select * from Win32_VideoController").Get();var currentHorizontalResolution = 0;var currentVerticalResolution = 0;foreach (var mo in moc){foreach (var item in mo.Properties){if (item.Name == "CurrentHorizontalResolution" && item.Value != null)currentHorizontalResolution = int.Parse((item.Value.ToString()));if (item.Name == "CurrentVerticalResolution" && item.Value != null)currentVerticalResolution = int.Parse((item.Value.ToString()));//gpu.Append($"{item.Name}:{item.Value}\r\n");}}//var res = gpu.ToString();//return res;return new Size(currentHorizontalResolution, currentVerticalResolution);}}public class MonitorHelper{/// <summary>/// 獲取DC句柄/// </summary>[DllImport("user32.dll")]static extern IntPtr GetDC(IntPtr hdc);/// <summary>/// 釋放DC句柄/// </summary>[DllImport("user32.dll", EntryPoint = "ReleaseDC")]static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hdc);/// <summary>/// 獲取句柄指定的數據/// </summary>[DllImport("gdi32.dll")]static extern int GetDeviceCaps(IntPtr hdc, int nIndex);/// <summary>/// 獲取設置的分辨率(修改縮放,該值不改變)/// {Width = 1920 Height = 1080}/// </summary>/// <returns></returns>public static Size GetResolution(){Size size = new Size();IntPtr hdc = GetDC(IntPtr.Zero);size.Width = GetDeviceCaps(hdc, DeviceCapsType.DESKTOPHORZRES);size.Height = GetDeviceCaps(hdc, DeviceCapsType.DESKTOPVERTRES);ReleaseDC(IntPtr.Zero, hdc);return size;}/// <summary>/// 獲取屏幕物理尺寸(mm,mm)/// {Width = 476 Height = 268}/// </summary>/// <returns></returns>public static Size GetScreenSize(){Size size = new Size();IntPtr hdc = GetDC(IntPtr.Zero);size.Width = GetDeviceCaps(hdc, DeviceCapsType.HORZSIZE);size.Height = GetDeviceCaps(hdc, DeviceCapsType.VERTSIZE);ReleaseDC(IntPtr.Zero, hdc);return size;}/// <summary>/// 獲取屏幕的尺寸---inch/// 21.5/// </summary>/// <returns></returns>public static float GetScreenInch(){Size size = GetScreenSize();double inch = Math.Round(Math.Sqrt(Math.Pow(size.Width, 2) + Math.Pow(size.Height, 2)) / 25.4, 1);return (float)inch;}}/// <summary>/// GetDeviceCaps 的 nidex值/// </summary>public class DeviceCapsType{public const int DRIVERVERSION = 0;public const int TECHNOLOGY = 2;public const int HORZSIZE = 4;//以毫米為單位的顯示寬度public const int VERTSIZE = 6;//以毫米為單位的顯示高度public const int HORZRES = 8;public const int VERTRES = 10;public const int BITSPIXEL = 12;public const int PLANES = 14;public const int NUMBRUSHES = 16;public const int NUMPENS = 18;public const int NUMMARKERS = 20;public const int NUMFONTS = 22;public const int NUMCOLORS = 24;public const int PDEVICESIZE = 26;public const int CURVECAPS = 28;public const int LINECAPS = 30;public const int POLYGONALCAPS = 32;public const int TEXTCAPS = 34;public const int CLIPCAPS = 36;public const int RASTERCAPS = 38;public const int ASPECTX = 40;public const int ASPECTY = 42;public const int ASPECTXY = 44;public const int SHADEBLENDCAPS = 45;public const int LOGPIXELSX = 88;//像素/邏輯英寸(水平)public const int LOGPIXELSY = 90; //像素/邏輯英寸(垂直)public const int SIZEPALETTE = 104;public const int NUMRESERVED = 106;public const int COLORRES = 108;public const int PHYSICALWIDTH = 110;public const int PHYSICALHEIGHT = 111;public const int PHYSICALOFFSETX = 112;public const int PHYSICALOFFSETY = 113;public const int SCALINGFACTORX = 114;public const int SCALINGFACTORY = 115;public const int VREFRESH = 116;public const int DESKTOPVERTRES = 117;//垂直分辨率public const int DESKTOPHORZRES = 118;//水平分辨率public const int BLTALIGNMENT = 119;}/// <summary>/// 屏幕信息/// </summary>public class GPUInfo{/// <summary>/// 當前分辨率/// </summary>public Size CurrentResolution { get; set; }/// <summary>/// 最大分辨率/// </summary>public Size MaxScreenResolution { get; set; }}#endregion#region 硬盤信息public partial class ComputerInfo{/// <summary>/// 磁盤信息/// </summary>public static List<DiskInfo> GetDiskInfo(){List<DiskInfo> diskInfos = new List<DiskInfo>();try{var moc = new ManagementClass("Win32_LogicalDisk").GetInstances();foreach (ManagementObject mo in moc){var diskInfo = new DiskInfo();var diskInfoType = diskInfo.GetType();var diskInfoFields = diskInfoType.GetProperties().ToList();foreach (var item in mo.Properties){if (diskInfoFields.Exists(f => f.Name == item.Name)){var p = diskInfoType.GetProperty(item.Name);p.SetValue(diskInfo, item.Value);}}diskInfos.Add(diskInfo);}//B轉GBfor (int i = 0; i < diskInfos.Count; i++){diskInfos[i].Size = Math.Round((double)(diskInfos[i].Size / 1024.0 / 1024.0 / 1024.0), 1);diskInfos[i].FreeSpace = Math.Round((double)(diskInfos[i].FreeSpace / 1024.0 / 1024.0 / 1024.0), 1);}}catch (Exception ex){}return diskInfos;}}/// <summary>/// 磁盤信息/// </summary>public class DiskInfo{/// <summary>/// 磁盤ID 如:D:/// </summary>public string DeviceID { get; set; }/// <summary>/// 驅動器類型。3為本地固定磁盤,2為可移動磁盤/// </summary>public uint DriveType { get; set; }/// <summary>/// 磁盤名稱。如:系統/// </summary>public string VolumeName { get; set; }/// <summary>/// 描述。如:本地固定磁盤/// </summary>public string Description { get; set; }/// <summary>/// 文件系統。如:NTFS/// </summary>public string FileSystem { get; set; }/// <summary>/// 磁盤容量(GB)/// </summary>public double Size { get; set; }/// <summary>/// 可用空間(GB)/// </summary>public double FreeSpace { get; set; }public override string ToString(){return $"{VolumeName}({DeviceID}), {FreeSpace}GB is available for {Size}GB in total, {FileSystem}, {Description}";}}#endregion

可以獲取下面這些信息:

ComputerCheck Info:
System Info:Windows 10 Enterprise, Enterprise, X64, Microsoft Windows 10.0.18363?
CPU Info:Intel(R) Core(TM) i3-8100 CPU @ 3.60GHz, 4 Core 4 Threads
RAM Info:12/15.8GB(75%)
GPU Info:1920*1080 / 1920*1080
Disk Info:系統(C:), 74.2GB is available for 238.1GB in total, NTFS, 本地固定磁盤
軟件(D:), 151.9GB is available for 300GB in total, NTFS, 本地固定磁盤
辦公(E:), 30.7GB is available for 300GB in total, NTFS, 本地固定磁盤
其它(F:), 256.3GB is available for 331.5GB in total, NTFS, 本地固定磁盤

參考文章:

WMI_04_常見的WMI類的屬性_wmi scsilogicalunit_fantongl的博客-CSDN博客

C#獲取計算機物理內存和可用內存大小封裝類SystemInfo_c# 獲得物理內存大小_CodingPioneer的博客-CSDN博客

https://www.cnblogs.com/pilgrim/p/15115925.html

win10各種版本英文名稱是什么? - 編程之家

https://www.cnblogs.com/dongweian/p/14182576.html

C# 使用WMI獲取所有服務的信息_c# wmi_FireFrame的博客-CSDN博客

WMI_02_常用WMI查詢列表_fantongl的博客-CSDN博客

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/41026.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/41026.shtml
英文地址,請注明出處:http://en.pswp.cn/news/41026.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

flinksql報錯 Cannot determine simple type name “org“

flink版本 1.15 報錯內容 2023-08-17 15:46:02 java.lang.RuntimeException: Could not instantiate generated class WatermarkGenerator$0at org.apache.flink.table.runtime.generated.GeneratedClass.newInstance(GeneratedClass.java:74)at org.apache.flink.table.runt…

低功耗、5Mbps、RS-422 接口電路MS2583/MS2583M

MS2583/MS2583M 是一款低功耗、 5Mbps 、高 ESD 能力的 RS422 通訊接口電路。 在接收狀態下&#xff0c;其功耗僅為 0.3mA 左右。 A/B 端 ESD 耐壓可達 15kV &#xff0c;且無自激現象。當輸出短路發生大電 流導致電路溫度過高時&#xff0c;開啟內部過溫保護電路&…

go 使用 make 初始化 slice 切片使用注意

go 使用 make 初始化 slice 切片 時指定長度和不指定長度的情況 指定長度 package mainimport "fmt"func main() {s1 : make([]int, 5)data : []int{1, 2, 3}for _, v : range data {s1 append(s1, v)}fmt.Println(s1) }// 以上代碼會輸出 // [0 0 0 0 0 1 2 3] //…

vue中的路由緩存和解決方案

路由緩存的原因 解決方法 推薦方案二&#xff0c;使用鉤子函數beforeRouteUpdate&#xff0c;每次路由更新前執行

手寫spring筆記

手寫spring筆記 《Spring 手擼專欄》筆記 IoC部分 Bean初始化和屬性注入 Bean的信息封裝在BeanDefinition中 /*** 用于記錄Bean的相關信息*/ public class BeanDefinition {/*** Bean對象的類型*/private Class beanClass;/*** Bean對象中的屬性信息*/private PropertyVal…

MFC第三十天 通過CToolBar類開發文字工具欄和工具箱、GDI+邊框填充以及基本圖形的繪制方法、圖形繪制過程的反色線模型和實色模型

文章目錄 CControlBar通過CToolBar類開發文字工具欄和工具箱CMainFrame.hCAppCMainFrm.cppCMainView.hCMainView.cppCEllipse.hCEllipse.cppCLine.hCLine.cppCRRect .hCRRect .cpp CControlBar class AFX_NOVTABLE CControlBar : public CWnd{DECLARE_DYNAMIC(CControlBar)pro…

OC調用Swift編寫的framework

一、前言 隨著swift趨向穩定&#xff0c;越來越多的公司都開始用swift來編寫蘋果相關的業務了&#xff0c;關于swift的利弊這里就不多說了。這里詳細介紹OC調用swift編寫的framework庫的步驟 二、制作framework 1、新建項目&#xff0c;選擇framework 2、填寫framework的名稱…

AutoHotkey:定時刪除目錄下指定分鐘以前的文件,帶UI界面

刪除指定目錄下&#xff0c;所有在某個指定分鐘以前的文件&#xff0c;可以用來清理經常生成很多文件的目錄&#xff0c;但又需要保留最新的一部分文件 支持拖放目錄到界面 能夠記憶設置&#xff0c;下次啟動后不用重新設置&#xff0c;可以直接開始 應用場景比如&#xff1a…

WinForm內嵌Unity3D

Unity3D可以C#腳本進行開&#xff0c;使用vstu2013.msi插件&#xff0c;可以實現在VS2013中的調試。在開發完成后&#xff0c;由于項目需要&#xff0c;需要將Unity3D嵌入到WinForm中。WinForm中的UnityWebPlayer Control可以載入Unity3D。先看效果圖。 一、為了能夠動態設置ax…

【boost網絡庫從青銅到王者】第五篇:asio網絡編程中的同步讀寫的客戶端和服務器示例

文章目錄 1、簡介2、客戶端設計3、服務器設計3.1、session函數3.2、StartListen函數3、總體設計 4、效果測試5、遇到的問題5.1、服務器遇到的問題5.1.1、不用顯示調用bind綁定和listen監聽函數5.1.2、出現 Error occured!Error code : 10009 .Message: 提供的文件句柄無效。 [s…

Failed to execute goal org.apache.maven.plugins

原因&#xff1a; 這個文件D:\java\maven\com\ruoyi\pg-student\maven-metadata-local.xml出了問題 解決&#xff1a; 最簡單的直接刪除D:\java\maven\com\ruoyi\pg-student\maven-metadata-local.xml重新打包 或者把D:\java\maven\com\ruoyi\pg-student這個目錄下所有文件…

性能測試場景設計

性能測試場景設計&#xff0c;是性能測試中的重要概念&#xff0c;性能測試場景設計&#xff0c;目的是要描述如何執行性能測試。 通常來講&#xff0c;性能測試場景設計主要會涉及以下部分&#xff1a; 并發用戶數是多少&#xff1f; 測試剛開始時&#xff0c;以什么樣的速率…

Spring WebFlux 的詳細介紹

Spring WebFlux 是基于響應式編程的框架&#xff0c;用于構建異步、非阻塞的 Web 應用程序。它是Spring框架的一部分&#xff0c;專注于支持響應式編程范式&#xff0c;使應用程序能夠高效地處理大量的并發請求和事件。 以下是關于 Spring WebFlux 的詳細介紹&#xff1a; 1. *…

go入門實踐五-實現一個https服務

文章目錄 前言生成證書申請免費的證書使用Go語言生成自簽CA證書 https的客戶端和服務端服務端代碼客戶端代碼 tls的客戶端和服務端服務端客戶端 前言 在公網中&#xff0c;我想加密傳輸的數據。(1)很自然&#xff0c;我想到了把數據放到http的請求中&#xff0c;然后通過tls確…

2023年京東寵物食品行業數據分析(京東大數據)

寵物食品市場需求主要來自于養寵規模&#xff0c;近年來由于我國寵物數量及養寵人群的規模均在不斷擴大&#xff0c;寵物相關產業和市場規模也在蓬勃發展&#xff0c;寵物食品市場也同樣保持正向增長。 根據鯨參謀電商數據分析平臺的相關數據顯示&#xff0c;2023年1月-7月&am…

vue5種模糊查詢方式

在Vue中&#xff0c;有多種方式可以實現模糊查詢。以下是五種常見的模糊查詢方式&#xff1a; 使用JavaScript的filter()方法&#xff1a;使用filter()方法可以對數組進行篩選&#xff0c;根據指定的條件進行模糊查詢。例如&#xff1a; data() {return {items: [{ name: App…

接口自動化測試(添加課程接口調試,調試合同上傳接口,合同列表查詢接口,批量執行)

1、我們把信息截取一下 1.1 添加一個新的請求 1.2 對整個請求進行保存&#xff0c;Ctrl S 2、這一次我們添加的是課程添加接口&#xff0c;以后一個接口完成&#xff0c;之后Ctrl S 就能夠保存 2.1 選擇方法 2.2 設置請求頭&#xff0c;參數數據后期我們通過配置設置就行 3、…

收銀一體化-億發2023智慧門店新零售營銷策略,實現全渠道運營

伴隨著互聯網電商行業的興起&#xff0c;以及用戶理念的改變&#xff0c;大量用戶從線下涌入線上&#xff0c;傳統的線下門店人流量急劇收縮&#xff0c;門店升級幾乎成為了每一個零售企業的發展之路。智慧門店新零售收銀解決方案是針對傳統零售企業面臨的諸多挑戰和問題&#…

Mathematica 與 Matlab 常見復雜指令集匯編

Mathematica 常見指令匯編 Mathematica 常見指令 NDSolve 求解結果的保存 sol NDSolve[{y[x] x^2, y[0] 0, g[x] -y[x]^2, g[0] 1}, {y, g}, {x, 0, 1}]; numericSoly sol[[1, 1, 2]]; numericSolg sol[[1, 2, 2]]; data Table[{x, numericSoly[x], numericSolg[x]},…

JVM——類加載器

回顧一下類加載過程 類加載過程&#xff1a;加載->連接->初始化。連接過程又可分為三步:驗證->準備->解析。 一個非數組類的加載階段&#xff08;加載階段獲取類的二進制字節流的動作&#xff09;是可控性最強的階段&#xff0c;這一步我們可以去完成還可以自定義…