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,内存等)的更多相关文章

  1. 通过wmi获取本地硬件信息的一些疑问。

    通过wmi获取本地硬件信息的一些疑问. http://bbs.csdn.net/topics/391017789 http://blog.csdn.net/xcntime/article/detail ...

  2. C#获取电脑硬件信息(CPU ID、主板ID、硬盘ID、BIOS编号)

    最近学习过程中,想到提取系统硬件信息做一些验证,故而对网上提到的利用.NET System.Management类获取硬件信息做了进一步的学习.验证.验证是分别在4台电脑,XP SP3系统中进行,特将 ...

  3. c# 获取机器硬件信息 (硬盘,cpu,内存等)

    using System; using System.Collections.Generic; using System.Globalization; using System.Management; ...

  4. C++ WMI获取系统硬件信息(CPU/DISK/NetWork etc)

    官网找到一个例子,根据例子修改下可以获取很多信息 #define _WIN32_DCOM #include <iostream> using namespace std; #include ...

  5. PYTHON 获取机器硬件信息及状态

    #!/usr/bin/env python # encoding: utf-8 from optparse import OptionParser import os import re import ...

  6. Unity3D的SystemInfo类,用于获取运行设备硬件信息(CPU、显卡、类型等)

    SystemInfo类中的静态变量:   中文显示: Rendering.CopyTextureSupport copyTextureSupport:(只读)支持多种复制纹理功能的情况. string ...

  7. android 获取系统硬件信息

    一,首先设置权限访问: <uses-permission android:name="android.permission.READ_PHONE_STATE" />  ...

  8. python之psutil模块(获取系统性能信息(CPU,内存,磁盘,网络)

    一.psutil模块 1. psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等) ...

  9. 获取显卡硬件信息lspci -vnn | grep VGA -A 12

    lspci -vnn | grep VGA -A 12 lshw -C display lshw -c video | grep configuration glxinfo | grep OpenGL ...

随机推荐

  1. unity shader在小米2s上的问题

    一个很简单的用mask裁剪图片的效果: mask: 被裁剪图片: 正确的效果: 在小米2s上测,其中有一台小米2s出现花屏: 手机型号: shader如下: Shader "UI/Trans ...

  2. 【转】ASP.NET的OnClientClick与OnClick事件【解决了“识别用户在对话框里面选yes或no的问题”】

    OnClientClick是客户端事件方法.一般采用JavaScript来进行处理.也就是直接在IE端运行.一点击就运行. OnClick事件是服务器端事件处理方法,在服务器端,也就是IIS中运行.点 ...

  3. ManifoldJS

    微软推出开源工具ManifoldJS,可以自动将Web App转换成各种平台的App(安卓.iOS.Chrome OS.Windows). ManifoldJS通过获取网站meta-data信息,即可 ...

  4. JSP页面中<%! %>和<% %>的区别

    JSP声明语句:<%!声明语句%>,通常声明全局变量.常量.方法.类JSP Scriptlet:<%java代码%>,其中可包含局部变量.java语句JSP表达式:<%= ...

  5. eclipse luna maven搭建spring mvc

    1. 环境配置 a)         Java 1.7 b)         Eclipse luna c)         Maven3.2.5 d)         Spring 4.1.4 2. ...

  6. java 反射机制01

    // */ // ]]>   java反射机制01 Table of Contents 1 反射机制 2 反射成员 2.1 java.lang.Class 2.2 Constructor 2.3 ...

  7. 战胜忧虑<3>——学会接受不可避免的事实。

    学会接受不可避免的事实. 对必然的事情愉快地承受,就像杨柳承受风雨,水接受一切容器,我们也要承受一切事实. 故事: 在美国庆祝陆军在北非获胜的那一天,我接到国防部送来的一封电报,我的侄儿——我最爱的一 ...

  8. android studio提示unable to run mksdcard sdk

    如题,android studio提示unable to run mksdcard sdk sudo apt-

  9. TMS320C54x系列DSP的CPU与外设——第8章 流水线

    第8章 流水线 本章描述了TMS320C54x DSP流水线的操作,列出了对不同寄存器操作时的流水线延迟周期.(对应英语原文第7章) 8.1 流水线操作 TMS320C54x DSP有一个6段的指令流 ...

  10. 获取URL参数

    function GetQueryString(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]*)( ...