本文通过一个Demo,讲解如何通过C#获取操作系统相关的信息,如内存大小,CPU大小,机器名,环境变量等操作系统软件、硬件相关信息,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点:

  • Environment 提供有关当前环境和平台的信息以及操作它们的方法。
  • ManagementClass 表示公共信息模型 (CIM) 管理类。管理类是一个 WMI 类,如 Win32_LogicalDisk 和 Win32_Process,前者表示磁盘驱动器,后者表示进程(如 Notepad.exe)。通过该类的成员,可以使用特定的 WMI 类路径访问 WMI 数据。

效果图

系统信息 :获取如系统目录,平台标识,登录用户名,盘符,所在的域 等信息

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

特殊目录:桌面,我的文档,收藏夹,等目录,是不是很熟悉

操作系统:以下是获取CPU的信息,如型号,名称,个数,速度,厂商等信息【还可以获取其他如内存,硬盘等信息】

核心代码

代码如下:

 namespace DemoEnvironment
{
public partial class MainFrom : Form
{
public MainFrom()
{
InitializeComponent();
} private void MainFrom_Load(object sender, EventArgs e)
{
string machineName = Environment.MachineName;
string osVersionName = GetOsVersion(Environment.OSVersion.Version);
string servicePack = Environment.OSVersion.ServicePack;
osVersionName = osVersionName + " " + servicePack;
string userName = Environment.UserName;
string domainName = Environment.UserDomainName;
string tickCount = (Environment.TickCount / ).ToString() + "s";
string systemPageSize = (Environment.SystemPageSize / ).ToString() + "KB";
string systemDir = Environment.SystemDirectory;
string stackTrace = Environment.StackTrace;
string processorCounter = Environment.ProcessorCount.ToString();
string platform = Environment.OSVersion.Platform.ToString();
string newLine = Environment.NewLine;
bool is64Os = Environment.Is64BitOperatingSystem;
bool is64Process = Environment.Is64BitProcess; string currDir = Environment.CurrentDirectory;
string cmdLine = Environment.CommandLine;
string[] drives = Environment.GetLogicalDrives();
//long workingSet = (Environment.WorkingSet / 1024);
this.lblMachineName.Text = machineName;
this.lblOsVersion.Text = osVersionName;
this.lblUserName.Text = userName;
this.lblDomineName.Text = domainName;
this.lblStartTime.Text = tickCount;
this.lblPageSize.Text = systemPageSize;
this.lblSystemDir.Text = systemDir;
this.lblLogical.Text = string.Join(",", drives);
this.lblProcesserCounter.Text = processorCounter;
this.lblPlatform.Text = platform;
this.lblNewLine.Text = newLine.ToString();
this.lblSystemType.Text = is64Os ? "64bit" : "32bit";
this.lblProcessType.Text = is64Process ? "64bit" : "32bit";
this.lblCurDir.Text = currDir;
this.lblCmdLine.Text = cmdLine;
this.lblWorkSet.Text = GetPhisicalMemory().ToString()+"MB";
//环境变量
// HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment
IDictionary dicMachine = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine);
this.rtbVaribles.AppendText(string.Format("{0}: {1}", "机器环境变量", newLine));
foreach (string str in dicMachine.Keys) {
string val = dicMachine[str].ToString();
this.rtbVaribles.AppendText(string.Format("{0}: {1}{2}", str, val, newLine));
}
this.rtbVaribles.AppendText(string.Format("{0}{1}", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", newLine));
// 环境变量存储在 Windows 操作系统注册表的 HKEY_CURRENT_USER\Environment 项中,或从其中检索。
IDictionary dicUser = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User);
this.rtbVaribles.AppendText(string.Format("{0}: {1}", "用户环境变量", newLine));
foreach (string str in dicUser.Keys)
{
string val = dicUser[str].ToString();
this.rtbVaribles.AppendText(string.Format("{0}: {1}{2}", str, val, newLine));
}
this.rtbVaribles.AppendText(string.Format("{0}{1}", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", newLine));
IDictionary dicProcess = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process);
this.rtbVaribles.AppendText(string.Format("{0}: {1}", "进程环境变量", newLine));
foreach (string str in dicProcess.Keys)
{
string val = dicProcess[str].ToString();
this.rtbVaribles.AppendText(string.Format("{0}: {1}{2}", str, val, newLine));
}
//特殊目录
string[] names = Enum.GetNames(typeof(Environment.SpecialFolder));
foreach (string name in names){ Environment.SpecialFolder sf;
if (Enum.TryParse<Environment.SpecialFolder>(name, out sf))
{
string folder = Environment.GetFolderPath(sf);
this.rtbFolders.AppendText(string.Format("{0}: {1}{2}", name, folder, newLine));
}
}
//获取其他硬件,软件信息
GetPhicnalInfo();
} private string GetOsVersion(Version ver) {
string strClient = "";
if (ver.Major == && ver.Minor == )
{
strClient = "Win XP";
}
else if (ver.Major == && ver.Minor == )
{
strClient = "Win Vista";
}
else if (ver.Major == && ver.Minor == )
{
strClient = "Win 7";
}
else if (ver.Major == && ver.Minor == )
{
strClient = "Win 2000";
}
else
{
strClient = "未知";
}
return strClient;
} /// <summary>
/// 获取系统内存大小
/// </summary>
/// <returns>内存大小(单位M)</returns>
private int GetPhisicalMemory()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象
searcher.Query = new SelectQuery("Win32_PhysicalMemory ", "", new string[] { "Capacity" });//设置查询条件
ManagementObjectCollection collection = searcher.Get(); //获取内存容量
ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator(); long capacity = ;
while (em.MoveNext())
{
ManagementBaseObject baseObj = em.Current;
if (baseObj.Properties["Capacity"].Value != null)
{
try
{
capacity += long.Parse(baseObj.Properties["Capacity"].Value.ToString());
}
catch
{
return ;
}
}
}
return (int)(capacity / / );
} /// <summary>
/// https://msdn.microsoft.com/en-us/library/aa394084(VS.85).aspx
/// </summary>
/// <returns></returns>
private int GetPhicnalInfo() {
ManagementClass osClass = new ManagementClass("Win32_Processor");//后面几种可以试一下,会有意外的收获//Win32_PhysicalMemory/Win32_Keyboard/Win32_ComputerSystem/Win32_OperatingSystem
foreach (ManagementObject obj in osClass.GetInstances())
{
PropertyDataCollection pdc = obj.Properties;
foreach (PropertyData pd in pdc) {
this.rtbOs.AppendText(string.Format("{0}: {1}{2}", pd.Name, pd.Value, "\r\n"));
}
}
return ;
}
}
}

工程下载

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

C# 获取操作系统相关的信息的更多相关文章

  1. 使用ttXactAdmin、ttSQLCmdCacheInfo、ttSQLCmdQueryPlan获取SQL相关具体信息[TimesTen运维]

    使用ttXactAdmin.ttSQLCmdCacheInfo.ttSQLCmdQueryPlan获取SQL相关具体信息,适合于tt11以上版本号. $ ttversion TimesTen Rele ...

  2. C# 获取操作系统相关信息

    1.获取操作系统版本(PC,PDA均支持) Environment.OSVersion 2.获取应用程序当前目录(PC支持) Environment.CurrentDirectory 3.列举本地硬盘 ...

  3. ios 获取设备相关的信息

    .获取设备的信息 UIDevice *device = [[UIDevice alloc] int]; NSString *name = device.name; //获取设备所有者的名称 NSStr ...

  4. Java 获取操作系统相关的内容

    package com.hikvision.discsetup.util; import java.lang.reflect.Field; import java.net.InetAddress; i ...

  5. ios 获取手机相关的信息

    获取手机信息      应用程序的名称和版本号等信息都保存在mainBundle的一个字典中,用下面代码可以取出来 //获取版本号 NSDictionary *infoDict = [[NSBundl ...

  6. snmp获取设备相关管理信息

    在本文中,作者将向我们展示如何用snmp代理监视网络设备,甚至发送软件警告. 网络上很多代理在为我们服务.只要我们开启UDP/161,162端口,这些代理就会以Management Informati ...

  7. C# 获取计算机cpu,硬盘,内存相关的信息

    using System;using System.Management; namespace MmPS.Common.Helper{ /// <summary> /// 获取计算机相关的 ...

  8. 获取本地的jvm信息,进行图形化展示

    package test1; import java.lang.management.CompilationMXBean; import java.lang.management.GarbageCol ...

  9. .NET Core 获取操作系统各种信息

    .NET Core 获取操作系统各种信息 一.前言 .NET Core 内置了一些API供我们获取操作系统.运行时.框架等信息.这些API不是很常用,所有有些小伙伴可能还不知道,这里做一些可能用到的获 ...

随机推荐

  1. ASP.NET Core微服务+Tabler前端框架搭建个人博客2--系统架构

    功能分析 在整个微服务架构的搭建过程中,我们需要做的第一步就是对服务进行拆分,将一个完整的系统模块化,通过对各个模块互联,共同完成一个系统的工作.既然要做到模块化,那么必须明白你的系统的需求到底是什么 ...

  2. ASP .NET CORE 根据环境变量支持多个 appsettings.json

    0.背景 在开发项目的过程当中,生产环境与调试环境的配置肯定是不一样的.拿个最简单的例子来说,比如连接字符串这种东西,调试环境肯定是不能连接生产数据库的.在之前的话,这种情况只能说是你 COPY 两个 ...

  3. linux 根据端口查看系统进程

    1.lsof -i:端口号 2.netstat -tunlp|grep 端口号 注意不同用户下,查看的进程不同

  4. visual Studio 2017 扩展开发(二)《菜单图标详解》

    在上一篇我们在菜单栏创建了一个菜单,菜单上显示了一个图标跟文本.那么我们自己创建的菜单如何修改自定义的菜单图标呢.下面娓娓道来..... 首先你要有一个图,创建一个32位的位图.这个位图的像素是16p ...

  5. ionic2 关于启动后白屏问题跟app启动慢的问题

    问题描述: 在ionic2下创建的项目打包生成apk,运行在真机上,进入启动页然后有5秒左右的白屏情况才进入首页,在真实项目中更严重,启动画面后更有时候十几秒都是白屏,体验性非常差. 在各种搜索之下, ...

  6. 使用 Infer.NET 进行概率编程

    本文介绍了如何使用 Infer.NET 进行概率性编程. 概率性编程是一种将自定义模型表示为计算机程序的机器学习方法. 借助它可以在模型中包含专业知识,使机器学习系统更易理解. 它还支持在线推断,即在 ...

  7. mysql 开发进阶篇系列 16 MySQL Server(myisam key_buffer)

    一.概述 mysql 提供了很多参数来进行服务器的设置,当服务第一次启动的时候,所有启动参数值都是系统默认的.这些参数在很多生产环境下并不能满足实际的应用需求.在这个系列中涉及到了liunx 服务器, ...

  8. IntelliJ IDEA 代码字体大小的快捷键设置放大缩小(很实用)(图文详解)

    不多说,直接上干货!  这是在设置IntelliJ IDEA 代码字体的快捷键设置缩小: 怎么达到的了,就是ctrl + 你的鼠标滑扭往下  这是在设置IntelliJ IDEA 代码字体的快捷键设置 ...

  9. R语言命令汇总

    > qqplot(spear,fastrankweight)> qqplot(spear,fastrankweight,main="title")> qqplot ...

  10. MFC控件GDI编程

    MFC控件GDI编程 一丶学习内容 1.了解常用的GDI函数绘图. 2.使用常用的画笔画刷. 二丶常用的GDI函数绘图 上方则为我们常用的GDI函数了. 画线 矩形. 以及圆 等等. 2.1 画线代码 ...