本文通过一个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_MACHINESystemCurrentControlSetControlSession ManagerEnvironment 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_USEREnvironment 项中,或从其中检索。 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, " ")); 154 } 155 } 156 return 0; 157 } 158 } 159 }
小例子,小知识 ,积跬步以至千里, 积小流以成江海。