通过WMI获取机器信息

PerformanceCounter的介绍就不多说了,MSDN上介绍的很详细: https://msdn.microsoft.com/zh-cn/library/system.diagnostics.performancecounter(v=vs.110).aspx

 //对PerformanceCounter进行封装
public class PerformanceCounterCollect
{
private PerformanceCounter counter = null;
public PerformanceCounterCollect(string categoryName, string counterName, string instanceName)
{
counter = new PerformanceCounter(categoryName, counterName, instanceName, ".");
try
{
Collect();//开启采集
System.Threading.Thread.Sleep();
}
catch { }
}
public float Collect()
{
try
{
return counter.NextValue();
}
catch (Exception ex)
{
return -;
}
}
}

收集CpuUtilization:new PerformanceCounterCollect("Processor", "% Processor Time", "_Total")

收集DiskReadSpeed: new PerformanceCounterCollect("PhysicalDisk", "Disk Read Bytes/sec", "_Total")

收集DiskWriteSpeed:new PerformanceCounterCollect("PhysicalDisk", "Disk Write Bytes/sec", "_Total")

收集MemoryAvailable:new PerformanceCounterCollect("Memory", "Available MBytes", "")

收集NetworkSendSpeed这个有一些繁琐,因为机器机器多网卡是很普遍的,要获取Enable的网卡,代码如下:

  var ethernetInstance = GetEthernetInstance();

   public static string GetEthernetInstance()
{
var result = new PerformanceCounterCategory("Network Interface");
var instanceNames = result.GetInstanceNames();
var ethernetDescriptions = GetEthernetDescriptions();
foreach (var instance in instanceNames)
{
if (ethernetDescriptions.Contains(instance))
{
return instance;
}
}
return "";
//throw new Exception("Not found enable ethernet instance.");
} public static List<string> GetEthernetDescriptions()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
List<string> descriptions = new List<string>();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
descriptions.Add(DesConvertInstance(mo["Description"].ToString()));
}
}
return descriptions;
}
static string DesConvertInstance(string description)
{
foreach (var ch in changeChars)
{
description = description.Replace(ch.Key, ch.Value);
}
return description;
}
static Dictionary<string, string> changeChars = new Dictionary<string, string>()
{
{"(", "[" },
{")", "]" },
{"#", "_" },
};

收集NetworkSendSpeed:new PerformanceCounterCollect("Network Interface", "Bytes Sent/sec", ethernetInstance)

收集NetworkReceivedSpeed: new PerformanceCounterCollect("Network Interface", "Bytes Received/sec", ethernetInstance)

WMI还有很多,大家有兴趣可以查看以下网址:

https://msdn.microsoft.com/en-us/library/dn792179(v=vs.85).aspx

上一篇:[No000083]文件与文件夹操作


下一篇:python文件、文件夹操作OS模块