本文通过一个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. 本地语音识别开源软件pocketsphinx调试总结

    1问题一: fatal error: pocketsphinx.h: No such file or directory 解决方法: $ cd /usr/include $ sudo ln -s /m ...

  2. 解决ios关于:ERROR Internal navigation rejected - <allow-navigation> not set for url='about:blank'

    在mac上,cordova打包ionic项目为苹果手机app出现 这个问题:ERROR Internal navigation rejected - <allow-navigation> ...

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

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

  4. Struts2框架(4)---Action类访问servlet

    Action类访问servlet Action类有三种方式servlet: (1)间接的方式访问Servlet API  ---使用ActionContext对象 (2)  实现接口,访问Action ...

  5. No principal was found in the response from the CAS server

    按网上的配置了 public String casServerUrlPrefix = "http://cas-server.com:8080/cas"; public String ...

  6. vue-11-路由嵌套-参数传递-路由高亮

    1, 新建vue-router 项目 vue init webpack vue-router-test 是否创建路由: 是 2, 添加路由列表页 在 component下创建 NavList 页面 & ...

  7. 为什么使用SLF4J比使用log4j或者java.util.logging更好

    1.SLF4j是什么? SLF4J 并没有真正地实现日志记录,它只是一个允许你使用任何java日志记录库的抽象适配层. 如果你正在编写内部或者外部使用的API或者应用库的话,如果使用了slf4j,那么 ...

  8. 实战!基于lamp安装Discuz论坛-技术流ken

    简介 我前面的博客已经详细介绍了lamp采用yum安装以及编译安装的方式,这篇博客将基于yum安装的lamp架构来实战安装Discuz论坛,你可以任选其一来完成. 系统环境 centos7.5 服务器 ...

  9. Python图像处理之验证码识别

      在上一篇博客Python图像处理之图片文字识别(OCR)中我们介绍了在Python中如何利用Tesseract软件来识别图片中的英文与中文,本文将具体介绍如何在Python中利用Tesseract ...

  10. Python图像处理之图片文字识别(OCR)

    OCR与Tesseract介绍   将图片翻译成文字一般被称为光学文字识别(Optical Character Recognition,OCR).可以实现OCR 的底层库并不多,目前很多库都是使用共同 ...