码迷,mamicode.com
首页 > Windows程序 > 详细

Window系统性能获取帮助类

时间:2016-08-10 12:16:05      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:

前言:

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

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


代码:

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

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Diagnostics;
  4 using System.IO;
  5 using System.Linq;
  6 using System.Management;
  7 using System.Net;
  8 using System.Net.NetworkInformation;
  9 using System.Text;
 10 using System.Text.RegularExpressions;
 11 using System.Threading;
 12 using System.Threading.Tasks;
 13 using Echevil;
 14 using Microsoft.VisualBasic.Devices;
 15 using SharpPcap;
 16 using TLZ.OldSite.DB.MongoDB.Model;
 17 
 18 namespace TLZ.Helper
 19 {
 20     /// <summary>
 21     /// 获取操作系统任务管理器
 22     /// 信息的帮助类
 23     /// </summary>
 24     public class ProcessHelper
 25     {
 26         private readonly PerformanceCounter _cpu;
 27         private readonly ComputerInfo _cinf;
 28         private readonly string _ip;
 29         private readonly NetworkInterface[] _interfaceCard;
 30         private string _uploadInternet = "0";//上行默认数值
 31         private string _downloadInternet = "0";//下行默认数值
 32         public ProcessInternet _procInfo = null;
 33         public ProcessHelper()
 34         {
 35             _cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
 36             _cinf = new ComputerInfo();
 37             _ip = GetIPAddress();
 38             _interfaceCard = NetworkInterface.GetAllNetworkInterfaces();
 39             _procInfo = new ProcessInternet();
 40         }
 41 
 42         #region IP获取
 43         public string GetIPAddress()
 44         {
 45             try
 46             {
 47                 //获取IP地址 
 48                 string st = "";
 49                 ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
 50                 ManagementObjectCollection moc = mc.GetInstances();
 51                 foreach (ManagementObject mo in moc)
 52                 {
 53                     if ((bool)mo["IPEnabled"] == true)
 54                     {
 55                         System.Array ar;
 56                         ar = (System.Array)(mo.Properties["IpAddress"].Value);
 57                         st = ar.GetValue(0).ToString();
 58                         break;
 59                     }
 60                 }
 61                 moc = null;
 62                 mc = null;
 63                 return st;
 64             }
 65             catch
 66             {
 67                 return "unknow";
 68             }
 69             finally
 70             {
 71             }
 72         }
 73         #endregion
 74 
 75         #region 获取系统内存信息
 76         public SystemMemories GetSystemMemory()
 77         {
 78             var cinf = this._cinf;
 79             var used_mem = cinf.TotalPhysicalMemory - cinf.AvailablePhysicalMemory;
 80             var mb_mem = used_mem.ConvertBytes(2);
 81             var pmem = Convert.ToUInt64(mb_mem).ConvertBytes(1);
 82             var memoryUsageRate = Math.Round((double)(used_mem / Convert.ToDecimal(cinf.TotalPhysicalMemory) * 100), 0);
 83             var memoryALLCountGB = cinf.TotalPhysicalMemory.ConvertBytes(3);
 84             return new SystemMemories
 85             {
 86                 MemoryUsageRate = memoryUsageRate,
 87                 MemoryUsageGB = pmem,
 88                 MemoryUsageMB = mb_mem,
 89                 MemoryALLCountGB = memoryALLCountGB,
 90                 DateTimeNow = DateTime.Now
 91             };
 92         }
 93         #endregion
 94 
 95         #region 获取系统CPU信息
 96         public SystemCpu GetSystemCpu()
 97         {
 98             var cpuUsageRate = Math.Round(this._cpu.NextValue(), 0);
 99             return new SystemCpu
100             {
101                 CpuUsageRate = cpuUsageRate,
102                 DateTimeNow = DateTime.Now
103             };
104         }
105         #endregion
106 
107         #region 获取系统硬盘
108         public List<SystemHdd> GetSystemHdd()
109         {
110             List<SystemHdd> systemHdd = new List<SystemHdd>();
111             List<SystemHddContext> listInfo = GetDiskListInfo();
112             if (listInfo != null && listInfo.Count > 0)
113             {
114                 foreach (SystemHddContext disk in listInfo)
115                 {
116                     systemHdd.Add(new SystemHdd
117                     {
118                         HddName = disk.PartitionName,
119                         AllSpace = ManagerDoubleValue(disk.SumSpace, 1),
120                         UseSpace = ManagerDoubleValue(disk.SumSpace - disk.FreeSpace, 1),
121                         SurplusSpace = ManagerDoubleValue(disk.FreeSpace, 1),
122                         DateTimeNow = DateTime.Now
123                     });
124                 }
125             }
126             return systemHdd;
127 
128         }
129         private List<SystemHddContext> GetDiskListInfo()
130         {
131             List<SystemHddContext> list = null;
132             //指定分区的容量信息
133             try
134             {
135                 SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");
136 
137                 ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);
138 
139                 ManagementObjectCollection diskcollection = searcher.Get();
140                 if (diskcollection != null && diskcollection.Count > 0)
141                 {
142                     list = new List<SystemHddContext>();
143                     SystemHddContext harddisk = null;
144                     foreach (ManagementObject disk in searcher.Get())
145                     {
146                         int nType = Convert.ToInt32(disk["DriveType"]);
147                         if (nType != Convert.ToInt32(DriveType.Fixed))
148                         {
149                             continue;
150                         }
151                         else
152                         {
153                             harddisk = new SystemHddContext();
154                             harddisk.FreeSpace = Convert.ToDouble(disk["FreeSpace"]) / (1024 * 1024 * 1024);
155                             harddisk.SumSpace = Convert.ToDouble(disk["Size"]) / (1024 * 1024 * 1024);
156                             harddisk.PartitionName = disk["DeviceID"].ToString();
157                             list.Add(harddisk);
158                         }
159                     }
160                 }
161             }
162             catch (Exception)
163             {
164 
165             }
166             return list;
167         }
168         public double ManagerDoubleValue(double _value, int Length)
169         {
170             if (Length < 0)
171             {
172                 Length = 0;
173             }
174             return System.Math.Round(_value, Length);
175         }
176         #endregion
177 
178         #region 获取系统PING
179 
180         public SystemPing GetSystemPing(string pingIP)
181         {
182             var model = new SystemPing() { };
183             model.ThisIP = this._ip;
184             model.PingIP = pingIP;
185             model.DateTimeNow = DateTime.Now;
186 
187             Process p = new Process();
188             p.StartInfo.FileName = "cmd.exe";
189             p.StartInfo.UseShellExecute = false;
190             p.StartInfo.RedirectStandardInput = true;
191             p.StartInfo.RedirectStandardOutput = true;
192             p.StartInfo.RedirectStandardError = true;
193             p.StartInfo.CreateNoWindow = true;
194             p.Start();
195             p.StandardInput.WriteLine("ping -n 1 " + pingIP);
196             p.StandardInput.WriteLine("exit");
197             string strRst = p.StandardOutput.ReadToEnd();
198             strRst = Regex.Replace(strRst, @"\s", "");
199             if (strRst.IndexOf("Ping统计信息:") != -1)
200             {
201                 model.Status = "请求成功";
202                 string ziJie = strRst.Substring(strRst.IndexOf("字节=") + 3);
203                 model.PingByte = double.Parse(ziJie.Substring(0, ziJie.IndexOf("时间")));
204                 string shiJian = strRst.Substring(strRst.IndexOf("时间") + 3);
205                 model.PingDate = double.Parse(shiJian.Substring(0, shiJian.IndexOf("TTL=") - 2));
206                 string ttl = strRst.Substring(strRst.IndexOf("TTL=") + 4);
207                 model.PingTTL = double.Parse(ttl.Substring(0, ttl.IndexOf(pingIP + "的Ping统计信息:")));
208                 string yiFaSong = strRst.Substring(strRst.IndexOf("已发送=") + 4);
209                 model.PingFaSong = double.Parse(yiFaSong.Substring(0, yiFaSong.IndexOf("已接收=") - 1));
210                 string yiJieShou = strRst.Substring(strRst.IndexOf("已接收=") + 4);
211                 model.PingJieShou = double.Parse(yiJieShou.Substring(0, yiJieShou.IndexOf("丢失=") - 1));
212                 string diuShi = strRst.Substring(strRst.IndexOf("丢失=") + 3);
213                 model.PingDiuShi = double.Parse(diuShi.Substring(0, diuShi.IndexOf("(")));
214                 string diuShiLv = strRst.Substring(strRst.IndexOf("丢失=") + 3);
215                 model.PingDiuShiLv = diuShiLv.Substring(diuShiLv.IndexOf("(") + 1, diuShiLv.IndexOf("丢失)") - 2);
216             }
217             else if (strRst.IndexOf("请求超时。") != -1)
218             {
219                 model.Status = "请求超时";
220             }
221             else if (strRst.IndexOf("请求找不到主机") != -1)
222             {
223                 model.Status = "请求找不到主机";
224             }
225             else if (strRst.IndexOf("不知名主机") != -1)
226             {
227                 model.Status = "请求无法解析主机";
228             }
229             else
230             {
231                 model.Status = strRst;
232             }
233             p.Close();
234             return model;
235         }
236         #endregion
237 
238         #region 获取系统网络
239 
240         #region 方法一 不准确
241         /// <summary>
242         /// 获取系统网络流量情况:
243         /// 上传、下载
244         /// 此功能与网卡有关,目前暂不确定是否可行
245         /// </summary>
246         public SystemInternet GetSystemInternet()
247         {
248             //网卡不确定有几个,默认[0](本地连接)
249             //可在:控制面板-网络和 Internet-网络连接 中查看网卡
250             NetworkInterface nic = _interfaceCard[0];
251             IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics();
252 
253             int bytesSentSpeed = (int)(interfaceStats.BytesSent - double.Parse(_uploadInternet)) / 1024;
254             int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - double.Parse(_downloadInternet)) / 1024;
255 
256             _uploadInternet = interfaceStats.BytesSent.ToString();
257             _downloadInternet = interfaceStats.BytesReceived.ToString();
258 
259             return new SystemInternet
260             {
261                 InternetName = nic.Name,
262                 InternetType = nic.NetworkInterfaceType.ToString(),
263                 ALLDownloadByte = interfaceStats.BytesReceived.ToString(),
264                 AllUpLoadByte = interfaceStats.BytesSent.ToString(),
265                 UploadByte = bytesSentSpeed.ToString(),
266                 DownloadByte = bytesReceivedSpeed.ToString(),
267                 DateTimeNow = DateTime.Now
268             };
269         }
270         #endregion
271 
272         #region 方法二 已测试比较准确
273         //NetInfo netinfo = new NetInfo();
274         //string strNetName;
275         //PerformanceCounter pc;
276         //NetInfo.NetPerformanceStruct netInfoStruct;
277 
278 
279 
280         //List<NetInfo.NetInfoBaseStruct> lNetInfoBase = netinfo.GetNetInfoBase();
281 
282         //strNetName = lNetInfoBase[0].NetName;
283 
284         //#region 输出
285         //Console.Write("网卡名称:" + lNetInfoBase[0].NetName + "\n");
286         //Console.Write("IP地址IPV4:" + lNetInfoBase[0].IPAddress[0] + "\n");
287         //Console.Write("IP地址IPV6:" + lNetInfoBase[0].IPAddress[1] + "\n");
288         //Console.Write("MAC地址:" + lNetInfoBase[0].MACAddress + "\n");
289         //Console.Write("默认网关:" + lNetInfoBase[0].DefaultIPGateway + "\n");
290         //Console.Write("子网掩码:" + lNetInfoBase[0].IPSubnet + "\n");
291         //#endregion
292         //while (true)
293         //{
294         //    netInfoStruct = netinfo.GetNetPerformance(strNetName);
295         //    Console.Write("--------------------------开始---------------------------\n");
296         //    Console.Write("每秒字节总数:" + netInfoStruct.BytesTotal.ToString() + "\n");
297         //    Console.Write("每秒发送字节数:" + netInfoStruct.BytesSent.ToString() + "\n");
298         //    Console.Write("每秒接收字节数:" + netInfoStruct.BytesReceived.ToString() + "\n");
299         //    Console.Write("每秒包总数:" + netInfoStruct.PacketsTotal.ToString() + "\n");
300         //    Console.Write("每秒包发送数:" + netInfoStruct.PacketsSent.ToString() + "\n");
301         //    Console.Write("每秒发送单播包数:" + netInfoStruct.PacketsSentUnicast.ToString() + "\n");
302         //    Console.Write("每秒发送非单播包数:" + netInfoStruct.PacketsSentNonUnicast.ToString() + "\n");
303         //    Console.Write("丢弃的发送包数:" + netInfoStruct.PacketsSentDiscarded.ToString() + "\n");
304         //    Console.Write("错误的发送包数:" + netInfoStruct.PacketsSentErrors.ToString() + "\n");
305         //    Console.Write("每秒包接收数:" + netInfoStruct.PacketsReceived.ToString() + "\n");
306         //    Console.Write("每秒单播包接收数:" + netInfoStruct.PacketsReceivedUnicast.ToString() + "\n");
307         //    Console.Write("每秒非单播包接收总数:" + netInfoStruct.PacketsReceivedNonUnicast.ToString() + "\n");
308         //    Console.Write("丢弃的接收包数:" + netInfoStruct.PacketsReceivedDiscarded.ToString() + "\n");
309         //    Console.Write("错误的接收包数:" + netInfoStruct.PacketsReceivedErrors.ToString() + "\n");
310         //    Console.Write("--------------------------结束---------------------------\n");
311         //    Thread.Sleep(1000);
312         //}
313         #endregion
314 
315         #region 方法三 已测试比较准确
316         public SystemInternet GetSystemInternet(NetworkAdapter[] _adapters)
317         {
318             return new SystemInternet
319             {
320                 InternetName = _adapters[0].Name,
321                 UploadByte = (Math.Round(_adapters[0].UploadSpeedKbps, 2)).ToString(),
322                 DownloadByte = (Math.Round(_adapters[0].DownloadSpeedKbps, 2)).ToString(),
323                 DateTimeNow = DateTime.Now
324             };
325         }
326         #endregion
327         #endregion
328 
329         #region 获取进程内存
330         public ProcessMemories GetProcessMemories(string _processName)
331         {
332             if (Process.GetProcessesByName(_processName).Length > 0)
333             {
334                 using (var process = Process.GetProcessesByName(_processName)[0])
335                 {
336                     var p1 = new PerformanceCounter("Process", "Working Set - Private", _processName);
337                     var p3 = new PerformanceCounter("Process", "Private Bytes", _processName);
338                     return new ProcessMemories
339                     {
340                         ProcessName = _processName,
341                         ProcessSpecialUseKB = decimal.Round((Math.Round((decimal)p1.NextValue(), 0) / 1024) / 1000, 3),
342                         ProcessWorkingSetKB = decimal.Round((Math.Round((decimal)process.WorkingSet64 / 1024, 0)) / 1000, 3),
343                         ProcessSubmitKB = decimal.Round((Math.Round((decimal)p3.NextValue(), 0) / 1024) / 1000, 3),
344                         ProcessUsageRate = 0,
345                         DateTimeNow = DateTime.Now
346                     };
347                 }
348             }
349             else
350             {
351                 return new ProcessMemories();
352             }
353         }
354         #endregion
355 
356         #region 获取进程CPU
357         /// <summary>
358         /// 获取进程CPU
359         /// </summary>
360         /// <param name="_processName">进程名称</param>
361         /// <returns>ProcessCpu</returns>
362         public ProcessCpu GetProcessCpu(string _processName, int interval)
363         {
364             if (Process.GetProcessesByName(_processName).Length > 0)
365             {
366                 using (var pro = Process.GetProcessesByName(_processName)[0])
367                 {
368                     //上次记录的CPU时间
369                     var prevCpuTime = TimeSpan.Zero;
370                     //当前时间
371                     var curTime = pro.TotalProcessorTime;
372                     //间隔时间内的CPU运行时间除以逻辑CPU数量
373                     var value = (curTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
374                     prevCpuTime = curTime;
375                     return new ProcessCpu
376                     {
377                         ProcessName = _processName,
378                         ProcessUsageRate = value,
379                         DateTimeNow = DateTime.Now
380                     };
381                 }
382             }
383             else
384             {
385                 return new ProcessCpu();
386             }
387         }
388         #endregion
389 
390         #region 获取进程网络
391         /// <summary>
392         /// 进程网络
393         /// </summary>
394         /// <param name="_processName">进程名称</param>
395         /// <returns>ProcessInternet</returns>
396         public ProcessInternet GetProcessInternet(string _processName, int tntervalSecond)
397         {
398             if (Process.GetProcessesByName(_processName).Length > 0)
399             {
400                 using (var proModel = Process.GetProcessesByName(_processName)[0])
401                 {
402                     //进程id
403                     int pid = proModel.Id;
404                     //存放进程使用的端口号链表
405                     List<int> ports = new List<int>();
406 
407                     #region 获取指定进程对应端口号
408                     Process pro = new Process();
409                     pro.StartInfo.FileName = "cmd.exe";
410                     pro.StartInfo.UseShellExecute = false;
411                     pro.StartInfo.RedirectStandardInput = true;
412                     pro.StartInfo.RedirectStandardOutput = true;
413                     pro.StartInfo.RedirectStandardError = true;
414                     pro.StartInfo.CreateNoWindow = true;
415                     pro.Start();
416                     pro.StandardInput.WriteLine("netstat -ano");
417                     pro.StandardInput.WriteLine("exit");
418                     Regex reg = new Regex("\\s+", RegexOptions.Compiled);
419                     string line = null;
420                     ports.Clear();
421                     while ((line = pro.StandardOutput.ReadLine()) != null)
422                     {
423                         line = line.Trim();
424                         if (line.StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
425                         {
426                             line = reg.Replace(line, ",");
427                             string[] arr = line.Split(,);
428                             if (arr[4] == pid.ToString())
429                             {
430                                 string soc = arr[1];
431                                 int pos = soc.LastIndexOf(:);
432                                 int pot = int.Parse(soc.Substring(pos + 1));
433                                 ports.Add(pot);
434                             }
435                         }
436                         else if (line.StartsWith("UDP", StringComparison.OrdinalIgnoreCase))
437                         {
438                             line = reg.Replace(line, ",");
439                             string[] arr = line.Split(,);
440                             if (arr[3] == pid.ToString())
441                             {
442                                 string soc = arr[1];
443                                 int pos = soc.LastIndexOf(:);
444                                 int pot = int.Parse(soc.Substring(pos + 1));
445                                 ports.Add(pot);
446                             }
447                         }
448                     }
449                     pro.Close();
450                     #endregion
451 
452                     #region 获取本机IP地址
453                     //获取本机IP地址
454                     IPAddress[] addrList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
455                     string IP = addrList[0].ToString();
456                     //获取本机网络设备
457                     var devices = CaptureDeviceList.Instance;
458                     int count = devices.Count;
459                     if (count < 1)
460                     {
461                         throw new Exception("本机网络设备不存在");
462                     }
463                     #endregion
464 
465                     #region 开始抓包
466                     //开始抓包
467                     for (int i = 0; i < count; ++i)
468                     {
469                         for (int j = 0; j < ports.Count; ++j)
470                         {
471                             CaptureFlowRecv(IP, ports[j], i);
472                             CaptureFlowSend(IP, ports[j], i);
473                         }
474                     }
475                     #endregion
476 
477                     //long NetTotalBytes = _procInfo.NetTotalBytes;
478                     //long NetSendBytes = _procInfo.NetSendBytes;
479                     //long NetRecvBytes = _procInfo.NetRecvBytes;
480                     RefershInfo(tntervalSecond);
481                     _procInfo.Dispose();
482                     return new ProcessInternet
483                     {
484                         ProcessID = pid,
485                         ProcessName = proModel.ProcessName,
486                         NetSendBytes = _procInfo.NetSendBytes,
487                         NetRecvBytes = _procInfo.NetRecvBytes,
488                         NetTotalBytes = _procInfo.NetTotalBytes,
489                         DateTimeNow = DateTime.Now
490                     };
491 
492                     //最后要记得调用Dispose方法停止抓包并关闭设备
493 
494                 }
495             }
496             else
497             {
498                 return new ProcessInternet();
499             }
500         }
501         public void RefershInfo(int tntervalSecond)
502         {
503             _procInfo.NetRecvBytes = 0;
504             _procInfo.NetSendBytes = 0;
505             _procInfo.NetTotalBytes = 0;
506             Thread.Sleep(tntervalSecond);
507             _procInfo.NetTotalBytes = _procInfo.NetRecvBytes + _procInfo.NetSendBytes;
508         }
509         public void CaptureFlowSend(string IP, int portID, int deviceID)
510         {
511             ICaptureDevice device = (ICaptureDevice)CaptureDeviceList.New()[deviceID];
512 
513             device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalSend);
514 
515             int readTimeoutMilliseconds = 1000;
516             device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
517 
518             string filter = "src host " + IP + " and src port " + portID;
519             device.Filter = filter;
520             device.StartCapture();
521             _procInfo.dev.Add(device);
522         }
523         public void CaptureFlowRecv(string IP, int portID, int deviceID)
524         {
525             ICaptureDevice device = CaptureDeviceList.New()[deviceID];
526             device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalRecv);
527 
528             int readTimeoutMilliseconds = 1000;
529             device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
530 
531             string filter = "dst host " + IP + " and dst port " + portID;
532             device.Filter = filter;
533             device.StartCapture();
534             _procInfo.dev.Add(device);
535         }
536         private void device_OnPacketArrivalSend(object sender, CaptureEventArgs e)
537         {
538             var len = e.Packet.Data.Length;
539             _procInfo.NetSendBytes += len;
540         }
541         private void device_OnPacketArrivalRecv(object sender, CaptureEventArgs e)
542         {
543             var len = e.Packet.Data.Length;
544             _procInfo.NetRecvBytes += len;
545         }
546         #endregion
547     }
548 
549     /// <summary>
550     /// 获取系统网络
551     /// 另外一种方法,可能比上面那个准确点
552     /// </summary>
553     public class NetInfo
554     {
555         NetPerformanceStruct netPerformanceStruct;
556 
557         //定义PerformanceCounter
558         PerformanceCounter pcBytesTotal = new PerformanceCounter();
559         PerformanceCounter pcBytesSent = new PerformanceCounter();
560         PerformanceCounter pcBytesReceived = new PerformanceCounter();
561         PerformanceCounter pcPacketsTotal = new PerformanceCounter();
562         PerformanceCounter pcPacketsSent = new PerformanceCounter();
563         PerformanceCounter pcPacketsSentUnicast = new PerformanceCounter();
564         PerformanceCounter pcPacketsSentNonUnicast = new PerformanceCounter();
565         PerformanceCounter pcPacketsSentDiscarded = new PerformanceCounter();
566         PerformanceCounter pcPacketsSentErrors = new PerformanceCounter();
567         PerformanceCounter pcPacketsReceived = new PerformanceCounter();
568         PerformanceCounter pcPacketsReceivedUnicast = new PerformanceCounter();
569         PerformanceCounter pcPacketsReceivedNonUnicast = new PerformanceCounter();
570         PerformanceCounter pcPacketsReceivedDiscarded = new PerformanceCounter();
571         PerformanceCounter pcPacketsReceivedErrors = new PerformanceCounter();
572 
573         //构造函数
574         public NetInfo()
575         {
576 
577         }
578 
579 
580         //网络基础信息结构体
581         public struct NetInfoBaseStruct
582         {
583             public string NetName;  //网络名称
584             public string[] IPAddress;  //IP地址,包括IPv4和IPv6
585             public string MACAddress;  //MAC地址
586             public string IPSubnet;  //子网掩码
587             public string DefaultIPGateway;  //默认网关
588         }
589 
590 
591         //网络性能结构体
592         public struct NetPerformanceStruct
593         {
594             //字节
595             public float BytesTotal;  //每秒总字节数
596             public float BytesSent;  //每秒发送字节数
597             public float BytesReceived;  //每秒发送字节数
598 
599             //
600             public float PacketsTotal;  //每秒总包数
601 
602             //包发送
603             public float PacketsSent;  //每秒发送包数
604             public float PacketsSentUnicast;  //每秒发送单播包数
605             public float PacketsSentNonUnicast;  //每秒发送非单播包数
606             public float PacketsSentDiscarded;  //被丢弃的发送包数
607             public float PacketsSentErrors;  //错误的发送包数
608 
609 
610             //包接收
611             public float PacketsReceived;  //每秒接收包数
612             public float PacketsReceivedUnicast;  //每秒接收单播包数
613             public float PacketsReceivedNonUnicast;  //每秒接收非单播包数
614             public float PacketsReceivedDiscarded;  //被丢弃的接收包数
615             public float PacketsReceivedErrors;  //错误的接收包数
616 
617 
618 
619         }
620 
621 
622         //获取网络基本信息
623         /**/
624         /// <summary>
625         /// 获取网络基本信息
626         /// </summary>
627         /// <returns>包含网络基本信息结构体的列表</returns>
628         public List<NetInfoBaseStruct> GetNetInfoBase()
629         {
630             List<NetInfoBaseStruct> lNetInfo = new List<NetInfoBaseStruct>();
631             NetInfoBaseStruct netInfoBaseStruct;
632 
633 
634             ManagementObjectSearcher query =
635                             new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = ‘TRUE‘");
636             ManagementObjectCollection moCollection = query.Get();
637 
638             //遍历
639             foreach (ManagementObject mObject in moCollection)
640             {
641                 try
642                 {
643                     netInfoBaseStruct = new NetInfoBaseStruct();
644                     netInfoBaseStruct.NetName = mObject["Description"].ToString();
645                     netInfoBaseStruct.IPAddress = (string[])mObject["IPAddress"];
646                     netInfoBaseStruct.MACAddress = mObject["MACAddress"].ToString();
647                     //DefaultIPGateway
648                     if (mObject["DefaultIPGateway"] == null)  //如果默认网关只有一个则返回
649                     {
650                         netInfoBaseStruct.DefaultIPGateway = "";
651                     }
652                     else   //否则返回默认网关的数组(注:这里为了简单起见,只返回第一个网关)
653                     {
654                         netInfoBaseStruct.DefaultIPGateway = ((string[])mObject["DefaultIPGateway"])[0];
655                     }
656 
657                     //IPSubnet
658                     if (mObject["IPSubnet"] == null)
659                     {
660                         netInfoBaseStruct.IPSubnet = "";
661                     }
662                     else
663                     {
664                         netInfoBaseStruct.IPSubnet = ((string[])mObject["IPSubnet"])[0];
665                     }
666 
667                     lNetInfo.Add(netInfoBaseStruct);
668 
669                 }
670                 catch
671                 {
672                     //continue;
673                 }
674 
675             }
676 
677             return lNetInfo;
678         }
679 
680         //GetNetPerformance
681         public NetPerformanceStruct GetNetPerformance(string NetName)
682         {
683 
684             netPerformanceStruct = new NetPerformanceStruct();
685 
686             //定义CategoryName
687             pcBytesTotal.CategoryName = "Network Interface";
688             pcBytesSent.CategoryName = "Network Interface";
689             pcBytesReceived.CategoryName = "Network Interface";
690             pcPacketsTotal.CategoryName = "Network Interface";
691             pcPacketsSent.CategoryName = "Network Interface";
692             pcPacketsSentUnicast.CategoryName = "Network Interface";
693             pcPacketsSentNonUnicast.CategoryName = "Network Interface";
694             pcPacketsSentDiscarded.CategoryName = "Network Interface";
695             pcPacketsSentErrors.CategoryName = "Network Interface";
696             pcPacketsReceived.CategoryName = "Network Interface";
697             pcPacketsReceivedUnicast.CategoryName = "Network Interface";
698             pcPacketsReceivedNonUnicast.CategoryName = "Network Interface";
699             pcPacketsReceivedDiscarded.CategoryName = "Network Interface";
700             pcPacketsReceivedErrors.CategoryName = "Network Interface";
701 
702             //本次改进主要部分,主要思路是通过PerformanceCounterCategory这个类来获取Network Interface下
703             //的所有实例(即网卡名称),先将这个网卡名称处理掉所有的特殊字符,然后与传递进来的网卡名称(也处理掉特殊字符)
704             //进行比较,如果相同,就将符合格式的实例名称赋给网卡名称,接下去就是获取性能信息。。。
705             string[] instanceNames;
706             PerformanceCounterCategory mycat = new PerformanceCounterCategory("Network Interface");
707             try
708             {
709                 instanceNames = mycat.GetInstanceNames();
710                 string tmp;
711                 string tmpNormal;
712 
713                 for (int i = 0; i <= instanceNames.Length; i++)
714                 {
715                     tmp = Regex.Replace(instanceNames[i], @"[^a-zA-Z\d]", "");
716                     tmpNormal = Regex.Replace(NetName, @"[^a-zA-Z\d]", "");
717 
718                     if (tmp == tmpNormal)
719                     {
720                         NetName = instanceNames[i];
721                     }
722                 }
723             }
724             catch { }
725 
726             //定义InstanceName
727             pcBytesTotal.InstanceName = NetName;
728             pcBytesSent.InstanceName = NetName;
729             pcBytesReceived.InstanceName = NetName;
730             pcPacketsTotal.InstanceName = NetName;
731             pcPacketsSent.InstanceName = NetName;
732             pcPacketsSentUnicast.InstanceName = NetName;
733             pcPacketsSentNonUnicast.InstanceName = NetName;
734             pcPacketsSentDiscarded.InstanceName = NetName;
735             pcPacketsSentErrors.InstanceName = NetName;
736             pcPacketsReceived.InstanceName = NetName;
737             pcPacketsReceivedUnicast.InstanceName = NetName;
738             pcPacketsReceivedNonUnicast.InstanceName = NetName;
739             pcPacketsReceivedDiscarded.InstanceName = NetName;
740             pcPacketsReceivedErrors.InstanceName = NetName;
741 
742             //定义CounterName
743             pcBytesTotal.CounterName = "Bytes Total/sec";
744             pcBytesSent.CounterName = "Bytes Sent/sec";
745             pcBytesReceived.CounterName = "Bytes Received/sec";
746             pcPacketsTotal.CounterName = "Packets/sec";
747             pcPacketsSent.CounterName = "Packets Sent/sec";
748             pcPacketsSentUnicast.CounterName = "Packets Sent Unicast/sec";
749             pcPacketsSentNonUnicast.CounterName = "Packets Sent Non-Unicast/sec";
750             pcPacketsSentDiscarded.CounterName = "Packets Outbound Discarded";
751             pcPacketsSentErrors.CounterName = "Packets Outbound Errors";
752             pcPacketsReceived.CounterName = "Packets Received/sec";
753             pcPacketsReceivedUnicast.CounterName = "Packets Received Unicast/sec";
754             pcPacketsReceivedNonUnicast.CounterName = "Packets Received Non-Unicast/sec";
755             pcPacketsReceivedDiscarded.CounterName = "Packets Received Discarded";
756             pcPacketsReceivedErrors.CounterName = "Packets Received Errors";
757 
758             try
759             {
760                 //为结构体赋值
761                 netPerformanceStruct.BytesTotal = pcBytesTotal.NextValue();
762                 netPerformanceStruct.BytesSent = pcBytesSent.NextValue();
763                 netPerformanceStruct.BytesReceived = pcBytesReceived.NextValue();
764                 netPerformanceStruct.PacketsTotal = pcPacketsTotal.NextValue();
765                 netPerformanceStruct.PacketsSent = pcPacketsSent.NextValue();
766                 netPerformanceStruct.PacketsSentUnicast = pcPacketsSentUnicast.NextValue();
767                 netPerformanceStruct.PacketsSentNonUnicast = pcPacketsSentNonUnicast.NextValue();
768                 netPerformanceStruct.PacketsSentDiscarded = pcPacketsSentDiscarded.NextValue();
769                 netPerformanceStruct.PacketsSentErrors = pcPacketsSentErrors.NextValue();
770                 netPerformanceStruct.PacketsReceived = pcPacketsReceived.NextValue();
771                 netPerformanceStruct.PacketsReceivedUnicast = pcPacketsReceivedUnicast.NextValue();
772                 netPerformanceStruct.PacketsReceivedNonUnicast = pcPacketsReceivedNonUnicast.NextValue();
773                 netPerformanceStruct.PacketsReceivedDiscarded = pcPacketsReceivedDiscarded.NextValue();
774                 netPerformanceStruct.PacketsReceivedErrors = pcPacketsReceivedErrors.NextValue();
775             }
776             catch
777             {
778 
779             }
780 
781             return netPerformanceStruct;
782         }
783     }
784 
785 }

 

Window系统性能获取帮助类

标签:

原文地址:http://www.cnblogs.com/mcj-jy/p/5755895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!