c# WMI获取机器硬件信息(硬盘,cpu,内存等)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Management;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text; namespace UsbDemo
{
internal enum WmiType
{
Win32_Processor,
Win32_PerfFormattedData_PerfOS_Memory,
Win32_PhysicalMemory,
Win32_NetworkAdapterConfiguration,
Win32_LogicalDisk
} /// <summary>
/// 获取硬盘号和CPU号
/// </summary>
public class WmiHelper
{
public class MachineNumber
{
static Dictionary<string, ManagementObjectCollection> WmiDict =
new Dictionary<string, ManagementObjectCollection>(); static MachineNumber()
{
var names = Enum.GetNames(typeof(WmiType));
foreach (string name in names)
{
WmiDict.Add(name, new ManagementObjectSearcher("SELECT * FROM " + name).Get());
}
} /// <summary>
/// 获取硬盘号码
/// </summary>
/// <returns></returns>
public static string GetHardDiskNumber()
{
var query = WmiDict[WmiType.Win32_LogicalDisk.ToString()];
//var collection = query.Get(); string result = string.Empty;
foreach (var obj in query)
{
result = obj["VolumeSerialNumber"].ToString();
break;
} return result;
} /// <summary>
/// 获取CPU号码
/// </summary>
/// <returns></returns>
public static string GetCPUNumber()
{
var query = WmiDict[WmiType.Win32_Processor.ToString()];
//var collection = query.Get(); string result = string.Empty;
foreach (var obj in query)
{
result = obj["Processorid"].ToString();
break;
} return result;
} /// <summary>
/// 获取内存编号
/// </summary>
/// <returns></returns>
public static string GetMemoryNumber()
{
var query = WmiDict[WmiType.Win32_PhysicalMemory.ToString()];
//var collection = query.Get(); string result = string.Empty;
foreach (var obj in query)
{
result = obj["PartNumber"].ToString();
break;
}
return result;
} /// <summary>
/// 获取硬盘信息
/// </summary>
/// <returns></returns>
public static string HardDiskInfo()
{
DriveInfo[] drives = DriveInfo.GetDrives();
StringBuilder sr = new StringBuilder();
foreach (DriveInfo drive in drives)
{
if (drive.IsReady)
{
var val1 = (double)drive.TotalSize / / ;
var val2 = (double)drive.TotalFreeSpace / / ;
sr.AppendFormat("{0}:{2}/{3}MB/{4}MB/{1}%可用;" + Environment.NewLine, drive.Name, string.Format("{0:F2}", val2 / val1 * ), drive.DriveFormat, (long)val1, (long)val2);
}
}
return sr.ToString();
} /// <summary>
/// 获取操作系统信息
/// </summary>
/// <returns></returns>
public static string OSInfo()
{
StringBuilder sr = new StringBuilder();
sr.AppendFormat("机器名:{0};操作系统:{1};系统文件夹:{2};语言:{3};.NET:{4};当前目录:{5};当前用户:{6};",
Environment.MachineName,
Environment.OSVersion,
Environment.SystemDirectory,
CultureInfo.InstalledUICulture.EnglishName,
Environment.Version,
Environment.CurrentDirectory,
Environment.UserName);
return sr.ToString();
} /// <summary>
/// 获取网卡信息
/// </summary>
/// <returns></returns>
public static string NetworkInfo()
{
StringBuilder sr = new StringBuilder(); string host = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostByName(host);
sr.Append("IPv4:" + ipEntry.AddressList[] + "/"); sr.Append("IPv6:");
ipEntry = Dns.GetHostEntry(host);
sr.Append("IPv6:" + ipEntry.AddressList[] + ";"); sr.Append("MAC:");
var query = WmiDict[WmiType.Win32_NetworkAdapterConfiguration.ToString()];
foreach (var obj in query)
{
if (obj["IPEnabled"].ToString() == "True")
sr.Append(obj["MacAddress"] + ";");
} return sr.ToString();
} /// <summary>
/// 获取内存信息
/// </summary>
/// <returns></returns>
public static string MemoryInfo()
{
StringBuilder sr = new StringBuilder();
try
{
long capacity = ;
var query = WmiDict[WmiType.Win32_PhysicalMemory.ToString()];
int index = ;
foreach (var obj in query)
{
//sr.Append("内存" + index + "频率:" + obj["ConfiguredClockSpeed"] + ";");
capacity += Convert.ToInt64(obj["Capacity"]);
index++;
}
sr.Append("总物理内存:");
sr.Append(capacity / / + "MB;"); query = WmiDict[WmiType.Win32_PerfFormattedData_PerfOS_Memory.ToString()];
sr.Append("总可用内存:");
long available = ;
foreach (var obj in query)
{
available += Convert.ToInt64(obj.Properties["AvailableMBytes"].Value);
}
sr.Append(available + "MB;");
sr.AppendFormat("{0:F2}%可用; ", (double)available / (capacity / / ) * );
}
catch (Exception ex)
{
sr.Append("异常信息:" + ex.Message);
} return sr.ToString();
} /// <summary>
/// 获取CPU信息
/// </summary>
/// <returns></returns>
public static string CpuInfo()
{
StringBuilder sr = new StringBuilder(); var query = WmiDict[WmiType.Win32_Processor.ToString()];
foreach (var obj in query)
{
sr.Append("厂商:" + obj["Manufacturer"] + ";");
sr.Append("产品名称:" + obj["Name"] + ";");
sr.Append("最大频率:" + obj["MaxClockSpeed"] + ";");
sr.Append("当前频率:" + obj["CurrentClockSpeed"] + ";");
} return sr.ToString();
}
}
}
}
using System;
using System.Management; namespace UsbDemo
{
/// <summary>
/// USB控制设备类型
/// </summary>
public struct ProcessInfo
{
/// <summary>
/// USB控制器设备ID
/// </summary>
public String Antecedent; /// <summary>
/// USB即插即用设备ID
/// </summary>
public String Dependent;
} class ProcessWatcher
{
/// <summary>
/// USB插入事件监视
/// </summary>
private ManagementEventWatcher insertWatcher = null; /// <summary>
/// USB拔出事件监视
/// </summary>
private ManagementEventWatcher removeWatcher = null; /// <summary>
/// 添加USB事件监视器
/// </summary>
/// <param name="usbInsertHandler">USB插入事件处理器</param>
/// <param name="usbRemoveHandler">USB拔出事件处理器</param>
/// <param name="withinInterval">发送通知允许的滞后时间</param>
public Boolean AddUSBEventWatcher(EventArrivedEventHandler usbInsertHandler, EventArrivedEventHandler usbRemoveHandler, TimeSpan withinInterval)
{
try
{
////创建WQL事件查询,用于实例创建
//var qCreate = new WqlEventQuery("__InstanceCreationEvent",TimeSpan.FromSeconds(1),"TargetInstance ISA 'Win32_Process'"); ////创建WQL事件查询,用于实例删除
//var qDelete = new WqlEventQuery("__InstanceDeletionEvent",TimeSpan.FromSeconds(1), "TargetInstance ISA 'Win32_Process'"); ////创建事件查询的侦听器(ManagementEventWatcher)
//var wCreate = new ManagementEventWatcher(qCreate);
//var wDelete = new ManagementEventWatcher(qDelete); ////事件注册代码
//wCreate.EventArrived += (sender, e) =>
//{
// Console.WriteLine("运行:{0}", GetInfo(e.NewEvent));
//};
//wDelete.EventArrived += (sender, e) =>
//{
// Console.WriteLine("关闭:{0}", GetInfo(e.NewEvent));
//}; ////异步开始侦听
//wCreate.Start();
//wDelete.Start(); //Console.WriteLine("按任意键停止监控");
//Console.ReadKey(true); // 进程执行监视
if (usbInsertHandler != null)
{
WqlEventQuery InsertQuery = new WqlEventQuery("__InstanceCreationEvent", withinInterval, "TargetInstance ISA 'Win32_Process'");
insertWatcher = new ManagementEventWatcher( InsertQuery);
insertWatcher.EventArrived += usbInsertHandler;
insertWatcher.Start();
} // 进程结束监视
if (usbRemoveHandler != null)
{
WqlEventQuery RemoveQuery = new WqlEventQuery("__InstanceDeletionEvent", withinInterval, "TargetInstance ISA 'Win32_Process'");
removeWatcher = new ManagementEventWatcher( RemoveQuery);
removeWatcher.EventArrived += usbRemoveHandler;
removeWatcher.Start();
}
return true;
} catch (Exception)
{
RemoveUSBEventWatcher();
return false;
}
} /// <summary>
/// 移去USB事件监视器
/// </summary>
public void RemoveUSBEventWatcher()
{
if (insertWatcher != null)
{
insertWatcher.Stop();
insertWatcher = null;
} if (removeWatcher != null)
{
removeWatcher.Stop();
removeWatcher = null;
}
} //输出事件对应的ManagementBaseObject(本例中的Win32_Process实例)的信息
static string GetInfo(ManagementBaseObject mobj)
{
var instance = (ManagementBaseObject)mobj["TargetInstance"];
return string.Format("{0} - {1}", instance["Name"], DateTime.Now);
} /// <summary>
/// 定位发生插拔的USB设备
/// </summary>
/// <param name="e">USB插拔事件参数</param>
/// <returns>发生插拔现象的USB控制设备ID</returns>
public static ProcessInfo[] WhoControllerDevice(EventArrivedEventArgs e)
{
ManagementBaseObject instance = e.NewEvent["TargetInstance"] as ManagementBaseObject;
return new ProcessInfo[] { new ProcessInfo { Antecedent = instance["Name"].ToString(), Dependent = instance["Name"].ToString() } };
} }
}
http://blog.csdn.net/asciil/article/details/6931429
http://www.cnblogs.com/password1/p/5870751.html
c# WMI获取机器硬件信息(硬盘,cpu,内存等)的更多相关文章
- 通过wmi获取本地硬件信息的一些疑问。
通过wmi获取本地硬件信息的一些疑问. http://bbs.csdn.net/topics/391017789 http://blog.csdn.net/xcntime/article/detail ...
- C#获取电脑硬件信息(CPU ID、主板ID、硬盘ID、BIOS编号)
最近学习过程中,想到提取系统硬件信息做一些验证,故而对网上提到的利用.NET System.Management类获取硬件信息做了进一步的学习.验证.验证是分别在4台电脑,XP SP3系统中进行,特将 ...
- c# 获取机器硬件信息 (硬盘,cpu,内存等)
using System; using System.Collections.Generic; using System.Globalization; using System.Management; ...
- C++ WMI获取系统硬件信息(CPU/DISK/NetWork etc)
官网找到一个例子,根据例子修改下可以获取很多信息 #define _WIN32_DCOM #include <iostream> using namespace std; #include ...
- PYTHON 获取机器硬件信息及状态
#!/usr/bin/env python # encoding: utf-8 from optparse import OptionParser import os import re import ...
- Unity3D的SystemInfo类,用于获取运行设备硬件信息(CPU、显卡、类型等)
SystemInfo类中的静态变量: 中文显示: Rendering.CopyTextureSupport copyTextureSupport:(只读)支持多种复制纹理功能的情况. string ...
- android 获取系统硬件信息
一,首先设置权限访问: <uses-permission android:name="android.permission.READ_PHONE_STATE" /> ...
- python之psutil模块(获取系统性能信息(CPU,内存,磁盘,网络)
一.psutil模块 1. psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等) ...
- 获取显卡硬件信息lspci -vnn | grep VGA -A 12
lspci -vnn | grep VGA -A 12 lshw -C display lshw -c video | grep configuration glxinfo | grep OpenGL ...
随机推荐
- Linux体系结构(二): Linux系统层次
前一节内容大概介绍了一下Linux的历史由来,各大Linux发行厂商都是基于GNU项目下的所有开源软件,来构建各自己的Linux发行版本,一个完整的Linux发行版本大概可以分为以下四个层次结构: ...
- C# Timer用法及实例详解
C# Timer用法有哪些呢?我们在使用C# Timer时都会有自己的一些总结,那么这里向你介绍3种方法,希望对你了解和学习C# Timer使用的方法有所帮助. 关于C# Timer类 在C#里关于 ...
- 02-Java 数组和排序算法
一.Java 数组 1.数组定义:数组是有序数据的集合,数组中的每个元素具有相同的数组名和下标来做唯一标识. 2.数组的分类:一维.二维.三维. 3.数组声明及内存分配: 为数组分配内存空间:如果不分 ...
- xfs文件系统
引用http://blog.chinaunix.net/uid-522675-id-4665059.html xfs文件系统使用总结 1.3 xfs相关常用命令xfs_admin: 调整 xfs 文件 ...
- [Asp.net]说说密码框和只读框
作者:Wolfy出处:http://www.cnblogs.com/wolf-sun/ 引言 最近负责了一个公司的小项目,从前台到后代,都是自己搞的,为一个客户弄一个信息管理的小系统,虽然对界面什么的 ...
- linux中Zabbix邮件报警设置配置步骤
使用外部邮箱账号发送报警邮件设置 配置Zabbix服务端外部邮箱 vi /etc/mail.rc #编辑,添加以下信息 set from=xxx@163.com smtp=smtp.163.com s ...
- Linux-LNMP LAMP LNMPA
这个脚本是使用shell编写,为了快速在生产环境上部署lnmp/lamp/lnmpa(Linux.Nginx/Tengine.MySQL/MariaDB/Percona.PHP),适用于CentOS ...
- LINQ To SQL 语法及实例大全
http://blog.csdn.net/pan_junbiao/article/details/7015633 http://blog.csdn.net/pan_junbiao/article/de ...
- 【linux】grub详解
参数解释 1. default=0 # default后加一个数字n,表示n+1个“title”操作系统,0表示第一个“title” 的操作系统,以此类推. 2. timeout=0 # timeou ...
- HackerRank "Lucky Numbers"
Great learning for me:https://www.hackerrank.com/rest/contests/master/challenges/lucky-numbers/hacke ...