C#獲取操作系統相關的信息,如記憶體大小,CPU大小,機器名,環境變數等操作系統軟體、硬體相關信息 ...
本文通過一個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 }View Code
小例子,小知識 ,積跬步以至千里, 積小流以成江海。