C#C# 拿到操作系统相关的音信

正文通过一个Demo,讲解怎么着通过C#获取操作系统相关的音讯,如内存大小,CPU大小,机器名,环境变量等操作系统软件、硬件相关音信。

涉嫌到知识点:

  • Environment 提供关于当前环境和平台的新闻以及操作它们的法子。
  • ManagementClass 代表公共音讯模型 (CIM) 管理类。管理类是一个 WMI
    类,如 Win32_LogicalDisk 和
    Win32_Process,前者表示磁盘驱动器,后者表示经过(如 Notepad.exe)。通过此类的分子,可以使用一定的
    WMI 类路径访问 WMI 数据。

效率图如下:

系统音信 :得到如系统目录,平台标识,登录用户名,盘符,所在的域
等音信

C# 1

环境变量:即操作系统运行的参数,看看有没有眼下为之一亮的新闻

C# 2

独特目录:桌面,我的文档,收藏夹,等目录,是还是不是很熟识

C# 3

操作系统:以下是收获CPU的消息,如型号,名称,个数,速度,厂商等音讯【仍能够拿走别的如内存,硬盘等音信】

C# 4

代码如下:

C# 5C# 6

  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

C#,工程下载 

小例子,小知识 ,积跬步以至千里, 积小流以成江海。

相关文章