前言:

    这个是获取Windows系统的一些性能的帮助类,其中有:系统内存、硬盘、CPU、网络(个人测试还是比较准的)、Ping。单个进程的内存、Cpu、网络(不准)。

      最初在这个的时候在各种搜索引擎中查询相关资料,发现都有些问题,然后就改了下,总结下,为其他人提供下方便吧。


代码:

   代码中最后返回的实体不用管,改为自己的即可。

 using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Echevil;
using Microsoft.VisualBasic.Devices;
using SharpPcap;
using TLZ.OldSite.DB.MongoDB.Model; namespace TLZ.Helper
{
/// <summary>
/// 获取操作系统任务管理器
/// 信息的帮助类
/// </summary>
public class ProcessHelper
{
private readonly PerformanceCounter _cpu;
private readonly ComputerInfo _cinf;
private readonly string _ip;
private readonly NetworkInterface[] _interfaceCard;
private string _uploadInternet = "";//上行默认数值
private string _downloadInternet = "";//下行默认数值
public ProcessInternet _procInfo = null;
public ProcessHelper()
{
_cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
_cinf = new ComputerInfo();
_ip = GetIPAddress();
_interfaceCard = NetworkInterface.GetAllNetworkInterfaces();
_procInfo = new ProcessInternet();
} #region IP获取
public string GetIPAddress()
{
try
{
//获取IP地址
string st = "";
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
System.Array ar;
ar = (System.Array)(mo.Properties["IpAddress"].Value);
st = ar.GetValue().ToString();
break;
}
}
moc = null;
mc = null;
return st;
}
catch
{
return "unknow";
}
finally
{
}
}
#endregion #region 获取系统内存信息
public SystemMemories GetSystemMemory()
{
var cinf = this._cinf;
var used_mem = cinf.TotalPhysicalMemory - cinf.AvailablePhysicalMemory;
var mb_mem = used_mem.ConvertBytes();
var pmem = Convert.ToUInt64(mb_mem).ConvertBytes();
var memoryUsageRate = Math.Round((double)(used_mem / Convert.ToDecimal(cinf.TotalPhysicalMemory) * ), );
var memoryALLCountGB = cinf.TotalPhysicalMemory.ConvertBytes();
return new SystemMemories
{
MemoryUsageRate = memoryUsageRate,
MemoryUsageGB = pmem,
MemoryUsageMB = mb_mem,
MemoryALLCountGB = memoryALLCountGB,
DateTimeNow = DateTime.Now
};
}
#endregion #region 获取系统CPU信息
public SystemCpu GetSystemCpu()
{
var cpuUsageRate = Math.Round(this._cpu.NextValue(), );
return new SystemCpu
{
CpuUsageRate = cpuUsageRate,
DateTimeNow = DateTime.Now
};
}
#endregion #region 获取系统硬盘
public List<SystemHdd> GetSystemHdd()
{
List<SystemHdd> systemHdd = new List<SystemHdd>();
List<SystemHddContext> listInfo = GetDiskListInfo();
if (listInfo != null && listInfo.Count > )
{
foreach (SystemHddContext disk in listInfo)
{
systemHdd.Add(new SystemHdd
{
HddName = disk.PartitionName,
AllSpace = ManagerDoubleValue(disk.SumSpace, ),
UseSpace = ManagerDoubleValue(disk.SumSpace - disk.FreeSpace, ),
SurplusSpace = ManagerDoubleValue(disk.FreeSpace, ),
DateTimeNow = DateTime.Now
});
}
}
return systemHdd; }
private List<SystemHddContext> GetDiskListInfo()
{
List<SystemHddContext> list = null;
//指定分区的容量信息
try
{
SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery); ManagementObjectCollection diskcollection = searcher.Get();
if (diskcollection != null && diskcollection.Count > )
{
list = new List<SystemHddContext>();
SystemHddContext harddisk = null;
foreach (ManagementObject disk in searcher.Get())
{
int nType = Convert.ToInt32(disk["DriveType"]);
if (nType != Convert.ToInt32(DriveType.Fixed))
{
continue;
}
else
{
harddisk = new SystemHddContext();
harddisk.FreeSpace = Convert.ToDouble(disk["FreeSpace"]) / ( * * );
harddisk.SumSpace = Convert.ToDouble(disk["Size"]) / ( * * );
harddisk.PartitionName = disk["DeviceID"].ToString();
list.Add(harddisk);
}
}
}
}
catch (Exception)
{ }
return list;
}
public double ManagerDoubleValue(double _value, int Length)
{
if (Length < )
{
Length = ;
}
return System.Math.Round(_value, Length);
}
#endregion #region 获取系统PING public SystemPing GetSystemPing(string pingIP)
{
var model = new SystemPing() { };
model.ThisIP = this._ip;
model.PingIP = pingIP;
model.DateTimeNow = DateTime.Now; Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine("ping -n 1 " + pingIP);
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
strRst = Regex.Replace(strRst, @"\s", "");
if (strRst.IndexOf("Ping统计信息:") != -)
{
model.Status = "请求成功";
string ziJie = strRst.Substring(strRst.IndexOf("字节=") + );
model.PingByte = double.Parse(ziJie.Substring(, ziJie.IndexOf("时间")));
string shiJian = strRst.Substring(strRst.IndexOf("时间") + );
model.PingDate = double.Parse(shiJian.Substring(, shiJian.IndexOf("TTL=") - ));
string ttl = strRst.Substring(strRst.IndexOf("TTL=") + );
model.PingTTL = double.Parse(ttl.Substring(, ttl.IndexOf(pingIP + "的Ping统计信息:")));
string yiFaSong = strRst.Substring(strRst.IndexOf("已发送=") + );
model.PingFaSong = double.Parse(yiFaSong.Substring(, yiFaSong.IndexOf("已接收=") - ));
string yiJieShou = strRst.Substring(strRst.IndexOf("已接收=") + );
model.PingJieShou = double.Parse(yiJieShou.Substring(, yiJieShou.IndexOf("丢失=") - ));
string diuShi = strRst.Substring(strRst.IndexOf("丢失=") + );
model.PingDiuShi = double.Parse(diuShi.Substring(, diuShi.IndexOf("(")));
string diuShiLv = strRst.Substring(strRst.IndexOf("丢失=") + );
model.PingDiuShiLv = diuShiLv.Substring(diuShiLv.IndexOf("(") + , diuShiLv.IndexOf("丢失)") - );
}
else if (strRst.IndexOf("请求超时。") != -)
{
model.Status = "请求超时";
}
else if (strRst.IndexOf("请求找不到主机") != -)
{
model.Status = "请求找不到主机";
}
else if (strRst.IndexOf("不知名主机") != -)
{
model.Status = "请求无法解析主机";
}
else
{
model.Status = strRst;
}
p.Close();
return model;
}
#endregion #region 获取系统网络 #region 方法一 不准确
/// <summary>
/// 获取系统网络流量情况:
/// 上传、下载
/// 此功能与网卡有关,目前暂不确定是否可行
/// </summary>
public SystemInternet GetSystemInternet()
{
//网卡不确定有几个,默认[0](本地连接)
//可在:控制面板-网络和 Internet-网络连接 中查看网卡
NetworkInterface nic = _interfaceCard[];
IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics(); int bytesSentSpeed = (int)(interfaceStats.BytesSent - double.Parse(_uploadInternet)) / ;
int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - double.Parse(_downloadInternet)) / ; _uploadInternet = interfaceStats.BytesSent.ToString();
_downloadInternet = interfaceStats.BytesReceived.ToString(); return new SystemInternet
{
InternetName = nic.Name,
InternetType = nic.NetworkInterfaceType.ToString(),
ALLDownloadByte = interfaceStats.BytesReceived.ToString(),
AllUpLoadByte = interfaceStats.BytesSent.ToString(),
UploadByte = bytesSentSpeed.ToString(),
DownloadByte = bytesReceivedSpeed.ToString(),
DateTimeNow = DateTime.Now
};
}
#endregion #region 方法二 已测试比较准确
//NetInfo netinfo = new NetInfo();
//string strNetName;
//PerformanceCounter pc;
//NetInfo.NetPerformanceStruct netInfoStruct; //List<NetInfo.NetInfoBaseStruct> lNetInfoBase = netinfo.GetNetInfoBase(); //strNetName = lNetInfoBase[0].NetName; //#region 输出
//Console.Write("网卡名称:" + lNetInfoBase[0].NetName + "\n");
//Console.Write("IP地址IPV4:" + lNetInfoBase[0].IPAddress[0] + "\n");
//Console.Write("IP地址IPV6:" + lNetInfoBase[0].IPAddress[1] + "\n");
//Console.Write("MAC地址:" + lNetInfoBase[0].MACAddress + "\n");
//Console.Write("默认网关:" + lNetInfoBase[0].DefaultIPGateway + "\n");
//Console.Write("子网掩码:" + lNetInfoBase[0].IPSubnet + "\n");
//#endregion
//while (true)
//{
// netInfoStruct = netinfo.GetNetPerformance(strNetName);
// Console.Write("--------------------------开始---------------------------\n");
// Console.Write("每秒字节总数:" + netInfoStruct.BytesTotal.ToString() + "\n");
// Console.Write("每秒发送字节数:" + netInfoStruct.BytesSent.ToString() + "\n");
// Console.Write("每秒接收字节数:" + netInfoStruct.BytesReceived.ToString() + "\n");
// Console.Write("每秒包总数:" + netInfoStruct.PacketsTotal.ToString() + "\n");
// Console.Write("每秒包发送数:" + netInfoStruct.PacketsSent.ToString() + "\n");
// Console.Write("每秒发送单播包数:" + netInfoStruct.PacketsSentUnicast.ToString() + "\n");
// Console.Write("每秒发送非单播包数:" + netInfoStruct.PacketsSentNonUnicast.ToString() + "\n");
// Console.Write("丢弃的发送包数:" + netInfoStruct.PacketsSentDiscarded.ToString() + "\n");
// Console.Write("错误的发送包数:" + netInfoStruct.PacketsSentErrors.ToString() + "\n");
// Console.Write("每秒包接收数:" + netInfoStruct.PacketsReceived.ToString() + "\n");
// Console.Write("每秒单播包接收数:" + netInfoStruct.PacketsReceivedUnicast.ToString() + "\n");
// Console.Write("每秒非单播包接收总数:" + netInfoStruct.PacketsReceivedNonUnicast.ToString() + "\n");
// Console.Write("丢弃的接收包数:" + netInfoStruct.PacketsReceivedDiscarded.ToString() + "\n");
// Console.Write("错误的接收包数:" + netInfoStruct.PacketsReceivedErrors.ToString() + "\n");
// Console.Write("--------------------------结束---------------------------\n");
// Thread.Sleep(1000);
//}
#endregion #region 方法三 已测试比较准确
public SystemInternet GetSystemInternet(NetworkAdapter[] _adapters)
{
return new SystemInternet
{
InternetName = _adapters[].Name,
UploadByte = (Math.Round(_adapters[].UploadSpeedKbps, )).ToString(),
DownloadByte = (Math.Round(_adapters[].DownloadSpeedKbps, )).ToString(),
DateTimeNow = DateTime.Now
};
}
#endregion
#endregion #region 获取进程内存
public ProcessMemories GetProcessMemories(string _processName)
{
if (Process.GetProcessesByName(_processName).Length > )
{
using (var process = Process.GetProcessesByName(_processName)[])
{
var p1 = new PerformanceCounter("Process", "Working Set - Private", _processName);
var p3 = new PerformanceCounter("Process", "Private Bytes", _processName);
return new ProcessMemories
{
ProcessName = _processName,
ProcessSpecialUseKB = decimal.Round((Math.Round((decimal)p1.NextValue(), ) / ) / , ),
ProcessWorkingSetKB = decimal.Round((Math.Round((decimal)process.WorkingSet64 / , )) / , ),
ProcessSubmitKB = decimal.Round((Math.Round((decimal)p3.NextValue(), ) / ) / , ),
ProcessUsageRate = ,
DateTimeNow = DateTime.Now
};
}
}
else
{
return new ProcessMemories();
}
}
#endregion #region 获取进程CPU
/// <summary>
/// 获取进程CPU
/// </summary>
/// <param name="_processName">进程名称</param>
/// <returns>ProcessCpu</returns>
public ProcessCpu GetProcessCpu(string _processName, int interval)
{
if (Process.GetProcessesByName(_processName).Length > )
{
using (var pro = Process.GetProcessesByName(_processName)[])
{
//上次记录的CPU时间
var prevCpuTime = TimeSpan.Zero;
//当前时间
var curTime = pro.TotalProcessorTime;
//间隔时间内的CPU运行时间除以逻辑CPU数量
var value = (curTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * ;
prevCpuTime = curTime;
return new ProcessCpu
{
ProcessName = _processName,
ProcessUsageRate = value,
DateTimeNow = DateTime.Now
};
}
}
else
{
return new ProcessCpu();
}
}
#endregion #region 获取进程网络
/// <summary>
/// 进程网络
/// </summary>
/// <param name="_processName">进程名称</param>
/// <returns>ProcessInternet</returns>
public ProcessInternet GetProcessInternet(string _processName, int tntervalSecond)
{
if (Process.GetProcessesByName(_processName).Length > )
{
using (var proModel = Process.GetProcessesByName(_processName)[])
{
//进程id
int pid = proModel.Id;
//存放进程使用的端口号链表
List<int> ports = new List<int>(); #region 获取指定进程对应端口号
Process pro = new Process();
pro.StartInfo.FileName = "cmd.exe";
pro.StartInfo.UseShellExecute = false;
pro.StartInfo.RedirectStandardInput = true;
pro.StartInfo.RedirectStandardOutput = true;
pro.StartInfo.RedirectStandardError = true;
pro.StartInfo.CreateNoWindow = true;
pro.Start();
pro.StandardInput.WriteLine("netstat -ano");
pro.StandardInput.WriteLine("exit");
Regex reg = new Regex("\\s+", RegexOptions.Compiled);
string line = null;
ports.Clear();
while ((line = pro.StandardOutput.ReadLine()) != null)
{
line = line.Trim();
if (line.StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
{
line = reg.Replace(line, ",");
string[] arr = line.Split(',');
if (arr[] == pid.ToString())
{
string soc = arr[];
int pos = soc.LastIndexOf(':');
int pot = int.Parse(soc.Substring(pos + ));
ports.Add(pot);
}
}
else if (line.StartsWith("UDP", StringComparison.OrdinalIgnoreCase))
{
line = reg.Replace(line, ",");
string[] arr = line.Split(',');
if (arr[] == pid.ToString())
{
string soc = arr[];
int pos = soc.LastIndexOf(':');
int pot = int.Parse(soc.Substring(pos + ));
ports.Add(pot);
}
}
}
pro.Close();
#endregion #region 获取本机IP地址
//获取本机IP地址
IPAddress[] addrList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
string IP = addrList[].ToString();
//获取本机网络设备
var devices = CaptureDeviceList.Instance;
int count = devices.Count;
if (count < )
{
throw new Exception("本机网络设备不存在");
}
#endregion #region 开始抓包
//开始抓包
for (int i = ; i < count; ++i)
{
for (int j = ; j < ports.Count; ++j)
{
CaptureFlowRecv(IP, ports[j], i);
CaptureFlowSend(IP, ports[j], i);
}
}
#endregion //long NetTotalBytes = _procInfo.NetTotalBytes;
//long NetSendBytes = _procInfo.NetSendBytes;
//long NetRecvBytes = _procInfo.NetRecvBytes;
RefershInfo(tntervalSecond);
_procInfo.Dispose();
return new ProcessInternet
{
ProcessID = pid,
ProcessName = proModel.ProcessName,
NetSendBytes = _procInfo.NetSendBytes,
NetRecvBytes = _procInfo.NetRecvBytes,
NetTotalBytes = _procInfo.NetTotalBytes,
DateTimeNow = DateTime.Now
}; //最后要记得调用Dispose方法停止抓包并关闭设备 }
}
else
{
return new ProcessInternet();
}
}
public void RefershInfo(int tntervalSecond)
{
_procInfo.NetRecvBytes = ;
_procInfo.NetSendBytes = ;
_procInfo.NetTotalBytes = ;
Thread.Sleep(tntervalSecond);
_procInfo.NetTotalBytes = _procInfo.NetRecvBytes + _procInfo.NetSendBytes;
}
public void CaptureFlowSend(string IP, int portID, int deviceID)
{
ICaptureDevice device = (ICaptureDevice)CaptureDeviceList.New()[deviceID]; device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalSend); int readTimeoutMilliseconds = ;
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); string filter = "src host " + IP + " and src port " + portID;
device.Filter = filter;
device.StartCapture();
_procInfo.dev.Add(device);
}
public void CaptureFlowRecv(string IP, int portID, int deviceID)
{
ICaptureDevice device = CaptureDeviceList.New()[deviceID];
device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalRecv); int readTimeoutMilliseconds = ;
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); string filter = "dst host " + IP + " and dst port " + portID;
device.Filter = filter;
device.StartCapture();
_procInfo.dev.Add(device);
}
private void device_OnPacketArrivalSend(object sender, CaptureEventArgs e)
{
var len = e.Packet.Data.Length;
_procInfo.NetSendBytes += len;
}
private void device_OnPacketArrivalRecv(object sender, CaptureEventArgs e)
{
var len = e.Packet.Data.Length;
_procInfo.NetRecvBytes += len;
}
#endregion
} /// <summary>
/// 获取系统网络
/// 另外一种方法,可能比上面那个准确点
/// </summary>
public class NetInfo
{
NetPerformanceStruct netPerformanceStruct; //定义PerformanceCounter
PerformanceCounter pcBytesTotal = new PerformanceCounter();
PerformanceCounter pcBytesSent = new PerformanceCounter();
PerformanceCounter pcBytesReceived = new PerformanceCounter();
PerformanceCounter pcPacketsTotal = new PerformanceCounter();
PerformanceCounter pcPacketsSent = new PerformanceCounter();
PerformanceCounter pcPacketsSentUnicast = new PerformanceCounter();
PerformanceCounter pcPacketsSentNonUnicast = new PerformanceCounter();
PerformanceCounter pcPacketsSentDiscarded = new PerformanceCounter();
PerformanceCounter pcPacketsSentErrors = new PerformanceCounter();
PerformanceCounter pcPacketsReceived = new PerformanceCounter();
PerformanceCounter pcPacketsReceivedUnicast = new PerformanceCounter();
PerformanceCounter pcPacketsReceivedNonUnicast = new PerformanceCounter();
PerformanceCounter pcPacketsReceivedDiscarded = new PerformanceCounter();
PerformanceCounter pcPacketsReceivedErrors = new PerformanceCounter(); //构造函数
public NetInfo()
{ } //网络基础信息结构体
public struct NetInfoBaseStruct
{
public string NetName; //网络名称
public string[] IPAddress; //IP地址,包括IPv4和IPv6
public string MACAddress; //MAC地址
public string IPSubnet; //子网掩码
public string DefaultIPGateway; //默认网关
} //网络性能结构体
public struct NetPerformanceStruct
{
//字节
public float BytesTotal; //每秒总字节数
public float BytesSent; //每秒发送字节数
public float BytesReceived; //每秒发送字节数 //包
public float PacketsTotal; //每秒总包数 //包发送
public float PacketsSent; //每秒发送包数
public float PacketsSentUnicast; //每秒发送单播包数
public float PacketsSentNonUnicast; //每秒发送非单播包数
public float PacketsSentDiscarded; //被丢弃的发送包数
public float PacketsSentErrors; //错误的发送包数 //包接收
public float PacketsReceived; //每秒接收包数
public float PacketsReceivedUnicast; //每秒接收单播包数
public float PacketsReceivedNonUnicast; //每秒接收非单播包数
public float PacketsReceivedDiscarded; //被丢弃的接收包数
public float PacketsReceivedErrors; //错误的接收包数 } //获取网络基本信息
/**/
/// <summary>
/// 获取网络基本信息
/// </summary>
/// <returns>包含网络基本信息结构体的列表</returns>
public List<NetInfoBaseStruct> GetNetInfoBase()
{
List<NetInfoBaseStruct> lNetInfo = new List<NetInfoBaseStruct>();
NetInfoBaseStruct netInfoBaseStruct; ManagementObjectSearcher query =
new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
ManagementObjectCollection moCollection = query.Get(); //遍历
foreach (ManagementObject mObject in moCollection)
{
try
{
netInfoBaseStruct = new NetInfoBaseStruct();
netInfoBaseStruct.NetName = mObject["Description"].ToString();
netInfoBaseStruct.IPAddress = (string[])mObject["IPAddress"];
netInfoBaseStruct.MACAddress = mObject["MACAddress"].ToString();
//DefaultIPGateway
if (mObject["DefaultIPGateway"] == null) //如果默认网关只有一个则返回
{
netInfoBaseStruct.DefaultIPGateway = "";
}
else //否则返回默认网关的数组(注:这里为了简单起见,只返回第一个网关)
{
netInfoBaseStruct.DefaultIPGateway = ((string[])mObject["DefaultIPGateway"])[];
} //IPSubnet
if (mObject["IPSubnet"] == null)
{
netInfoBaseStruct.IPSubnet = "";
}
else
{
netInfoBaseStruct.IPSubnet = ((string[])mObject["IPSubnet"])[];
} lNetInfo.Add(netInfoBaseStruct); }
catch
{
//continue;
} } return lNetInfo;
} //GetNetPerformance
public NetPerformanceStruct GetNetPerformance(string NetName)
{ netPerformanceStruct = new NetPerformanceStruct(); //定义CategoryName
pcBytesTotal.CategoryName = "Network Interface";
pcBytesSent.CategoryName = "Network Interface";
pcBytesReceived.CategoryName = "Network Interface";
pcPacketsTotal.CategoryName = "Network Interface";
pcPacketsSent.CategoryName = "Network Interface";
pcPacketsSentUnicast.CategoryName = "Network Interface";
pcPacketsSentNonUnicast.CategoryName = "Network Interface";
pcPacketsSentDiscarded.CategoryName = "Network Interface";
pcPacketsSentErrors.CategoryName = "Network Interface";
pcPacketsReceived.CategoryName = "Network Interface";
pcPacketsReceivedUnicast.CategoryName = "Network Interface";
pcPacketsReceivedNonUnicast.CategoryName = "Network Interface";
pcPacketsReceivedDiscarded.CategoryName = "Network Interface";
pcPacketsReceivedErrors.CategoryName = "Network Interface"; //本次改进主要部分,主要思路是通过PerformanceCounterCategory这个类来获取Network Interface下
//的所有实例(即网卡名称),先将这个网卡名称处理掉所有的特殊字符,然后与传递进来的网卡名称(也处理掉特殊字符)
//进行比较,如果相同,就将符合格式的实例名称赋给网卡名称,接下去就是获取性能信息。。。
string[] instanceNames;
PerformanceCounterCategory mycat = new PerformanceCounterCategory("Network Interface");
try
{
instanceNames = mycat.GetInstanceNames();
string tmp;
string tmpNormal; for (int i = ; i <= instanceNames.Length; i++)
{
tmp = Regex.Replace(instanceNames[i], @"[^a-zA-Z\d]", "");
tmpNormal = Regex.Replace(NetName, @"[^a-zA-Z\d]", ""); if (tmp == tmpNormal)
{
NetName = instanceNames[i];
}
}
}
catch { } //定义InstanceName
pcBytesTotal.InstanceName = NetName;
pcBytesSent.InstanceName = NetName;
pcBytesReceived.InstanceName = NetName;
pcPacketsTotal.InstanceName = NetName;
pcPacketsSent.InstanceName = NetName;
pcPacketsSentUnicast.InstanceName = NetName;
pcPacketsSentNonUnicast.InstanceName = NetName;
pcPacketsSentDiscarded.InstanceName = NetName;
pcPacketsSentErrors.InstanceName = NetName;
pcPacketsReceived.InstanceName = NetName;
pcPacketsReceivedUnicast.InstanceName = NetName;
pcPacketsReceivedNonUnicast.InstanceName = NetName;
pcPacketsReceivedDiscarded.InstanceName = NetName;
pcPacketsReceivedErrors.InstanceName = NetName; //定义CounterName
pcBytesTotal.CounterName = "Bytes Total/sec";
pcBytesSent.CounterName = "Bytes Sent/sec";
pcBytesReceived.CounterName = "Bytes Received/sec";
pcPacketsTotal.CounterName = "Packets/sec";
pcPacketsSent.CounterName = "Packets Sent/sec";
pcPacketsSentUnicast.CounterName = "Packets Sent Unicast/sec";
pcPacketsSentNonUnicast.CounterName = "Packets Sent Non-Unicast/sec";
pcPacketsSentDiscarded.CounterName = "Packets Outbound Discarded";
pcPacketsSentErrors.CounterName = "Packets Outbound Errors";
pcPacketsReceived.CounterName = "Packets Received/sec";
pcPacketsReceivedUnicast.CounterName = "Packets Received Unicast/sec";
pcPacketsReceivedNonUnicast.CounterName = "Packets Received Non-Unicast/sec";
pcPacketsReceivedDiscarded.CounterName = "Packets Received Discarded";
pcPacketsReceivedErrors.CounterName = "Packets Received Errors"; try
{
//为结构体赋值
netPerformanceStruct.BytesTotal = pcBytesTotal.NextValue();
netPerformanceStruct.BytesSent = pcBytesSent.NextValue();
netPerformanceStruct.BytesReceived = pcBytesReceived.NextValue();
netPerformanceStruct.PacketsTotal = pcPacketsTotal.NextValue();
netPerformanceStruct.PacketsSent = pcPacketsSent.NextValue();
netPerformanceStruct.PacketsSentUnicast = pcPacketsSentUnicast.NextValue();
netPerformanceStruct.PacketsSentNonUnicast = pcPacketsSentNonUnicast.NextValue();
netPerformanceStruct.PacketsSentDiscarded = pcPacketsSentDiscarded.NextValue();
netPerformanceStruct.PacketsSentErrors = pcPacketsSentErrors.NextValue();
netPerformanceStruct.PacketsReceived = pcPacketsReceived.NextValue();
netPerformanceStruct.PacketsReceivedUnicast = pcPacketsReceivedUnicast.NextValue();
netPerformanceStruct.PacketsReceivedNonUnicast = pcPacketsReceivedNonUnicast.NextValue();
netPerformanceStruct.PacketsReceivedDiscarded = pcPacketsReceivedDiscarded.NextValue();
netPerformanceStruct.PacketsReceivedErrors = pcPacketsReceivedErrors.NextValue();
}
catch
{ } return netPerformanceStruct;
}
} }

Window系统性能获取帮助类的更多相关文章

  1. java进阶之反射:反射基础之如何获取一个类以及如何获取这个类的所有属性和方法(2)

    当我们知道一个类的对象,或者知道一个类的路径,或者指导这个类的名称的时候我们可以获取到这个类的类对象 当我们仅仅知道一个类的类对象的时候我们依然无法操作这个类,因为我们不知道这个类的属性,类的方法.那 ...

  2. Bug整理——$(window).height()获取到$(document).height()的问题

    想看解决方案不想看无聊乏味的bug解决过程的同学,请直接跳转到页面底部~ 今天在做项目的过程中遇到了一个BUG,项目中需要获取到浏览器客户区的高度以方便做一些适应性调整,代码如下: $(documen ...

  3. $(window).height()获取浏览器高度不准

    以前在开发的时候这样$(window).height()获取浏览器的高度一致不觉得有什么不对, 今天在做java开发的时候不知道为什么获取的高度很明显不对. 后来无意中想到一个文档模式不对的原因,于是 ...

  4. java中的反射机制,以及如何通过反射获取一个类的构造方法 ,成员变量,方法,详细。。

    首先先说一下类的加载,流程.只有明确了类这个对象的存在才可以更好的理解反射的原因,以及反射的机制. 一.  类的加载 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载,连接,初始化三 ...

  5. java 获取实体类对象属性值的方法

    在java中我们要获得实体类对象的属性,一般情况是将实体类中的属性私有化,然后再对外提供get()与set()方法,然后再获取实体类对象的属性的时候先把对象new出来,再用变量名.get()的方法得到 ...

  6. php反射机制获取未知类的详细信息

    使用ReflectionClass就可以获取未知类的详细信息 demo: require("hello.php"); $class = new ReflectionClass(&q ...

  7. Java反射机制(获取Class对象的三种方式+获取Class中的构造函数进行对象的初始化+获取反射类的字段+获取反射类的一般方法)

    反射技术其实就是动态加载一个指定的类,并获取该类中的所有内容.而且将字节码文件封装成对象,并将字节码文件中的内容都封装成对象,这样便于操作这些成员,简单来说:反射技术可以对一个类进行解剖,反射大大增强 ...

  8. 获取C++类成员变量的地址偏移

    今天有在校学生问怎么获取类中的成员变量的地址偏移量,这个应该是很多初学C++的人很好奇的问题.以前我在学校的时候,也有过这种需求.忘了当时是要写什么“奇怪的程序”了,反正需要获取一个类的成员变量的地址 ...

  9. Delphi中获取某类的祖先类及其所在单元名称(使用GetTypeData(PClass.ClassInfo)函数,并且该类是从TPersistent类的派生类才可以这么使用)

    前几天在CSDN社区看到一篇<如何得到自身单元名称>的帖子,其中一位名为sdzeng网友给出了答案.受此启发,自己写了一个函数,用来获取指定类的所有祖先类的名称及其所在的单元名称. //参 ...

随机推荐

  1. 从零自学Hadoop(19):HBase介绍及安装

    阅读目录 序 介绍 安装 系列索引 本文版权归mephisto和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作. 文章是哥(mephisto)写的,SourceLink 序 上一篇, ...

  2. 常用ASCII CHR碼對照

    因為開發需求,把對照表留下來一下. Chr(0) Null Chr(29) 分组符 Chr(38) & Chr(48) 0 Chr(8) 退格 Chr(30) 記錄分離符號 Chr(39) ‘ ...

  3. Spark——SparkContext简单分析

    本篇文章就要根据源码分析SparkContext所做的一些事情,用过Spark的开发者都知道SparkContext是编写Spark程序用到的第一个类,足以说明SparkContext的重要性:这里先 ...

  4. plain framework 商业版 开发总结2 项目管理器

    任何事情都有三个阶段,分析.制作.质检的过程.在程序中就分为设计.编码.调试(测试)三个阶段,其中设计最为重要,设计的不好会导致编码和调试重复,甚至最后又回到了设计的过程.为了不会重复返工,所以设计的 ...

  5. BZOJ 3555: [Ctsc2014]企鹅QQ [字符串哈希]【学习笔记】

    3555: [Ctsc2014]企鹅QQ Time Limit: 20 Sec  Memory Limit: 256 MBSubmit: 2046  Solved: 749[Submit][Statu ...

  6. codevs 3288 积木大赛

    题目描述 Description 春春幼儿园举办了一年一度的"积木大赛".今年比赛的内容是搭建一座宽度为 n 的大厦,大厦可以看成由 n 块宽度为1的积木组成,第i块积木的最终高度 ...

  7. [LeetCode] Delete Node in a BST 删除二叉搜索树中的节点

    Given a root node reference of a BST and a key, delete the node with the given key in the BST. Retur ...

  8. [LeetCode] Paint House II 粉刷房子之二

    There are a row of n houses, each house can be painted with one of the k colors. The cost of paintin ...

  9. VehicleCamera解读

    坐标系: z-axis ^ | | y-axis | / | / |/ +----------------> x-axis 围绕Z轴旋转叫做偏航角,Yaw:围绕X轴旋转叫做 俯仰角,Pitch: ...

  10. com.panie 项目开发随笔_功能任务设计(2016.12.28)

    (一) 第一个菜单 做什么好呢? 1)上次 在研究的功能 是 爬虫,需要将定时爬虫的任务加进来 2)博客的页面,也需要重新布局出来 3)需要做一个,添加博客的页面 (二) 那就先做博客管理吧! 先添加 ...