C# 獲取作業系統和硬體的資訊
阿新 • • 發佈:2021-12-17
本文通過一個Demo,講解如何通過C#獲取作業系統相關的資訊,如記憶體大小,CPU大小,機器名,環境變數等作業系統軟體、硬體相關資訊,僅供學習分享使用,如有不足之處,還請指正。
涉及知識點:
- Environment 提供有關當前環境和平臺的資訊以及操作它們的方法。
- ManagementClass 表示公共資訊模型 (CIM) 管理類。管理類是一個 WMI 類,如 Win32_LogicalDisk 和 Win32_Process,前者表示磁碟驅動器,後者表示程序(如Notepad.exe)。通過該類的成員,可以使用特定的 WMI 類路徑訪問 WMI 資料。
效果圖
系統資訊 :獲取如系統目錄,平臺標識,登入使用者名稱,碟符,所在的域 等資訊
環境變數:即作業系統執行的引數,看看有沒有眼前為之一亮的資訊
特殊目錄:桌面,我的文件,收藏夾,等目錄,是不是很熟悉
作業系統:以下是獲取CPU的資訊,如型號,名稱,個數,速度,廠商等資訊【還可以獲取其他如記憶體,硬碟等資訊】
核心程式碼
程式碼如下:
1 namespace DemoEnvironment 2 { 3 public partial class MainFrom : Form 4 { 5 public MainFrom() 6 { 7 InitializeComponent();8 } 9 10 private void MainFrom_Load(object sender, EventArgs e) 11 { 12 string machineName = Environment.MachineName; 13 string osVersionName = GetOsVersion(Environment.OSVersion.Version); 14 string servicePack = Environment.OSVersion.ServicePack;15 osVersionName = osVersionName + " " + servicePack; 16 string userName = Environment.UserName; 17 string domainName = Environment.UserDomainName; 18 string tickCount = (Environment.TickCount / 1000).ToString() + "s"; 19 string systemPageSize = (Environment.SystemPageSize / 1024).ToString() + "KB"; 20 string systemDir = Environment.SystemDirectory; 21 string stackTrace = Environment.StackTrace; 22 string processorCounter = Environment.ProcessorCount.ToString(); 23 string platform = Environment.OSVersion.Platform.ToString(); 24 string newLine = Environment.NewLine; 25 bool is64Os = Environment.Is64BitOperatingSystem; 26 bool is64Process = Environment.Is64BitProcess; 27 28 string currDir = Environment.CurrentDirectory; 29 string cmdLine = Environment.CommandLine; 30 string[] drives = Environment.GetLogicalDrives(); 31 //long workingSet = (Environment.WorkingSet / 1024); 32 this.lblMachineName.Text = machineName; 33 this.lblOsVersion.Text = osVersionName; 34 this.lblUserName.Text = userName; 35 this.lblDomineName.Text = domainName; 36 this.lblStartTime.Text = tickCount; 37 this.lblPageSize.Text = systemPageSize; 38 this.lblSystemDir.Text = systemDir; 39 this.lblLogical.Text = string.Join(",", drives); 40 this.lblProcesserCounter.Text = processorCounter; 41 this.lblPlatform.Text = platform; 42 this.lblNewLine.Text = newLine.ToString(); 43 this.lblSystemType.Text = is64Os ? "64bit" : "32bit"; 44 this.lblProcessType.Text = is64Process ? "64bit" : "32bit"; 45 this.lblCurDir.Text = currDir; 46 this.lblCmdLine.Text = cmdLine; 47 this.lblWorkSet.Text = GetPhisicalMemory().ToString()+"MB"; 48 //環境變數 49 // HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment 50 IDictionary dicMachine = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine); 51 this.rtbVaribles.AppendText(string.Format("{0}: {1}", "機器環境變數", newLine)); 52 foreach (string str in dicMachine.Keys) { 53 string val = dicMachine[str].ToString(); 54 this.rtbVaribles.AppendText(string.Format("{0}: {1}{2}", str, val, newLine)); 55 } 56 this.rtbVaribles.AppendText(string.Format("{0}{1}", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", newLine)); 57 // 環境變數儲存在 Windows 作業系統登錄檔的 HKEY_CURRENT_USER\Environment 項中,或從其中檢索。 58 IDictionary dicUser = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User); 59 this.rtbVaribles.AppendText(string.Format("{0}: {1}", "使用者環境變數", newLine)); 60 foreach (string str in dicUser.Keys) 61 { 62 string val = dicUser[str].ToString(); 63 this.rtbVaribles.AppendText(string.Format("{0}: {1}{2}", str, val, newLine)); 64 } 65 this.rtbVaribles.AppendText(string.Format("{0}{1}", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", newLine)); 66 IDictionary dicProcess = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process); 67 this.rtbVaribles.AppendText(string.Format("{0}: {1}", "程序環境變數", newLine)); 68 foreach (string str in dicProcess.Keys) 69 { 70 string val = dicProcess[str].ToString(); 71 this.rtbVaribles.AppendText(string.Format("{0}: {1}{2}", str, val, newLine)); 72 } 73 //特殊目錄 74 string[] names = Enum.GetNames(typeof(Environment.SpecialFolder)); 75 foreach (string name in names){ 76 77 Environment.SpecialFolder sf; 78 if (Enum.TryParse<Environment.SpecialFolder>(name, out sf)) 79 { 80 string folder = Environment.GetFolderPath(sf); 81 this.rtbFolders.AppendText(string.Format("{0}: {1}{2}", name, folder, newLine)); 82 } 83 } 84 //獲取其他硬體,軟體資訊 85 GetPhicnalInfo(); 86 } 87 88 private string GetOsVersion(Version ver) { 89 string strClient = ""; 90 if (ver.Major == 5 && ver.Minor == 1) 91 { 92 strClient = "Win XP"; 93 } 94 else if (ver.Major == 6 && ver.Minor == 0) 95 { 96 strClient = "Win Vista"; 97 } 98 else if (ver.Major == 6 && ver.Minor == 1) 99 { 100 strClient = "Win 7"; 101 } 102 else if (ver.Major == 5 && ver.Minor == 0) 103 { 104 strClient = "Win 2000"; 105 } 106 else 107 { 108 strClient = "未知"; 109 } 110 return strClient; 111 } 112 113 /// <summary> 114 /// 獲取系統記憶體大小 115 /// </summary> 116 /// <returns>記憶體大小(單位M)</returns> 117 private int GetPhisicalMemory() 118 { 119 ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用於查詢一些如系統資訊的管理物件 120 searcher.Query = new SelectQuery("Win32_PhysicalMemory ", "", new string[] { "Capacity" });//設定查詢條件 121 ManagementObjectCollection collection = searcher.Get(); //獲取記憶體容量 122 ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator(); 123 124 long capacity = 0; 125 while (em.MoveNext()) 126 { 127 ManagementBaseObject baseObj = em.Current; 128 if (baseObj.Properties["Capacity"].Value != null) 129 { 130 try 131 { 132 capacity += long.Parse(baseObj.Properties["Capacity"].Value.ToString()); 133 } 134 catch 135 { 136 return 0; 137 } 138 } 139 } 140 return (int)(capacity / 1024 / 1024); 141 } 142 143 /// <summary> 144 /// https://msdn.microsoft.com/en-us/library/aa394084(VS.85).aspx 145 /// </summary> 146 /// <returns></returns> 147 private int GetPhicnalInfo() { 148 ManagementClass osClass = new ManagementClass("Win32_Processor");//後面幾種可以試一下,會有意外的收穫//Win32_PhysicalMemory/Win32_Keyboard/Win32_ComputerSystem/Win32_OperatingSystem 149 foreach (ManagementObject obj in osClass.GetInstances()) 150 { 151 PropertyDataCollection pdc = obj.Properties; 152 foreach (PropertyData pd in pdc) { 153 this.rtbOs.AppendText(string.Format("{0}: {1}{2}", pd.Name, pd.Value, "\r\n")); 154 } 155 } 156 return 0; 157 } 158 } 159 }
小例子,小知識 ,積跬步以至千里, 積小流以成江海。
出處:https://www.cnblogs.com/hsiang/p/6814839.html
您的資助是我最大的動力!
金額隨意,歡迎來賞!
付款後有任何問題請給我留言。
【關注我】。(●'◡'●)
如果對你有所幫助,贊助一杯咖啡!打 如果,您希望更容易地發現我的新部落格,不妨點選一下綠色通道的 付款後有任何問題請給我留言!!!因為,我的寫作熱情也離不開您的肯定與支援,感謝您的閱讀,我是【Jack_孟】!