[No0000112]ComputerInfo,C#獲取計算機信息(cpu使用率,內存占用率,硬盤,網絡信息)...

github地址:https://github.com/charygao/SmsComputerMonitor

軟件用于實時監控當前系統資源等情況,并調用接口,當資源被超額占用時,發送警報到個人手機;界面模擬Console的顯示方式,信息緩沖大小由配置決定;可以定制監控的資源,包括:

  • 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.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;namespace SmsComputerMonitor
{public class ComputerInfo{#region Fields and Propertiesprivate readonly ManagementScope _LocalManagementScope;private readonly PerformanceCounter _pcCpuLoad; //CPU計數器,全局private const int GwHwndfirst = 0;private const int GwHwndnext = 2;private const int GwlStyle = -16;private const int WsBorder = 8388608;private const int WsVisible = 268435456;#region CPU占用率/// <summary>///     獲取CPU占用率(系統CPU使用率)/// </summary>public float CpuLoad => _pcCpuLoad.NextValue();#endregion#region 本地主機名public string HostName => Dns.GetHostName();#endregion#region 本地IPV4列表public List<IPAddress> IpAddressV4S{get{var ipV4S = new List<IPAddress>();foreach (var address in Dns.GetHostAddresses(Dns.GetHostName()))if (address.AddressFamily == AddressFamily.InterNetwork)ipV4S.Add(address);return ipV4S;}}#endregion#region 本地IPV6列表public List<IPAddress> IpAddressV6S{get{var ipV6S = new List<IPAddress>();foreach (var address in Dns.GetHostAddresses(Dns.GetHostName()))if (address.AddressFamily == AddressFamily.InterNetworkV6)ipV6S.Add(address);return ipV6S;}}#endregion#region 可用內存/// <summary>///     獲取可用內存/// </summary>public long MemoryAvailable{get{long availablebytes = 0;var managementClassOs = new ManagementClass("Win32_OperatingSystem");foreach (var managementBaseObject in managementClassOs.GetInstances())if (managementBaseObject["FreePhysicalMemory"] != null)availablebytes = 1024 * long.Parse(managementBaseObject["FreePhysicalMemory"].ToString());return availablebytes;}}#endregion#region 物理內存/// <summary>///     獲取物理內存/// </summary>public long PhysicalMemory { get; }#endregion#region CPU個數/// <summary>///     獲取CPU個數/// </summary>// ReSharper disable once UnusedAutoPropertyAccessor.Globalpublic int ProcessorCount { get; }#endregion#region 已用內存大小public long SystemMemoryUsed => PhysicalMemory - MemoryAvailable;#endregion#endregion#region  Constructors/// <summary>///     構造函數,初始化計數器等/// </summary>public ComputerInfo(){_LocalManagementScope = new ManagementScope($"\\\\{HostName}\\root\\cimv2");//初始化CPU計數器_pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total") {MachineName = "."};_pcCpuLoad.NextValue();//CPU個數ProcessorCount = Environment.ProcessorCount;//獲得物理內存var managementClass = new ManagementClass("Win32_ComputerSystem");var managementObjectCollection = managementClass.GetInstances();foreach (var managementBaseObject in managementObjectCollection)if (managementBaseObject["TotalPhysicalMemory"] != null)PhysicalMemory = long.Parse(managementBaseObject["TotalPhysicalMemory"].ToString());}#endregion#region  Methods#region 結束指定進程/// <summary>///     結束指定進程/// </summary>/// <param name="pid">進程的 Process ID</param>public static void EndProcess(int pid){try{var process = Process.GetProcessById(pid);process.Kill();}catch (Exception exception){Console.WriteLine(exception);}}#endregion#region 查找所有應用程序標題/// <summary>///     查找所有應用程序標題/// </summary>/// <returns>應用程序標題范型</returns>public static List<string> FindAllApps(int handle){var apps = new List<string>();var hwCurr = GetWindow(handle, GwHwndfirst);while (hwCurr > 0){var IsTask = WsVisible | WsBorder;var lngStyle = GetWindowLongA(hwCurr, GwlStyle);var taskWindow = (lngStyle & IsTask) == IsTask;if (taskWindow){var length = GetWindowTextLength(new IntPtr(hwCurr));var sb = new StringBuilder(2 * length + 1);GetWindowText(hwCurr, sb, sb.Capacity);var strTitle = sb.ToString();if (!string.IsNullOrEmpty(strTitle))apps.Add(strTitle);}hwCurr = GetWindow(hwCurr, GwHwndnext);}return apps;}#endregionpublic static List<PerformanceCounterCategory> GetAllCategories(bool isPrintRoot = true,bool isPrintTree = true){var result = new List<PerformanceCounterCategory>();foreach (var category in PerformanceCounterCategory.GetCategories()){result.Add(category);if (isPrintRoot){PerformanceCounter[] categoryCounters;switch (category.CategoryType){case PerformanceCounterCategoryType.SingleInstance:categoryCounters = category.GetCounters();PrintCategoryAndCounters(category, categoryCounters, isPrintTree);break;case PerformanceCounterCategoryType.MultiInstance:var categoryCounterInstanceNames = category.GetInstanceNames();if (categoryCounterInstanceNames.Length > 0){categoryCounters = category.GetCounters(categoryCounterInstanceNames[0]);PrintCategoryAndCounters(category, categoryCounters, isPrintTree);}break;case PerformanceCounterCategoryType.Unknown:categoryCounters = category.GetCounters();PrintCategoryAndCounters(category, categoryCounters, isPrintTree);break;//default: break;
                    }}}return result;}/// <summary>///     獲取本地所有磁盤/// </summary>/// <returns></returns>public static DriveInfo[] GetAllLocalDriveInfo(){return DriveInfo.GetDrives();}/// <summary>///     獲取本機所有進程/// </summary>/// <returns></returns>public static Process[] GetAllProcesses(){return Process.GetProcesses();}public static List<PerformanceCounter> GetAppointedCategorieCounters(PerformanceCategoryEnums.PerformanceCategoryEnum categorieEnum, bool isPrintRoot = true,bool isPrintTree = true){var result = new List<PerformanceCounter>();var categorieName = PerformanceCategoryEnums.GetCategoryNameString(categorieEnum);if (PerformanceCounterCategory.Exists(categorieName)){var category = new PerformanceCounterCategory(categorieName);PerformanceCounter[] categoryCounters;switch (category.CategoryType){case PerformanceCounterCategoryType.Unknown:categoryCounters = category.GetCounters();result = categoryCounters.ToList();if (isPrintRoot)PrintCategoryAndCounters(category, categoryCounters, isPrintTree);break;case PerformanceCounterCategoryType.SingleInstance:categoryCounters = category.GetCounters();result = categoryCounters.ToList();if (isPrintRoot)PrintCategoryAndCounters(category, categoryCounters, isPrintTree);break;case PerformanceCounterCategoryType.MultiInstance:var categoryCounterInstanceNames = category.GetInstanceNames();if (categoryCounterInstanceNames.Length > 0){categoryCounters = category.GetCounters(categoryCounterInstanceNames[0]);result = categoryCounters.ToList();if (isPrintRoot)PrintCategoryAndCounters(category, categoryCounters, isPrintTree);}break;//default: break;
                }}return result;}/// <summary>///     獲取指定磁盤可用大小/// </summary>/// <param name="drive"></param>/// <returns></returns>public static long GetDriveAvailableFreeSpace(DriveInfo drive){return drive.AvailableFreeSpace;}/// <summary>///     獲取指定磁盤總空白大小/// </summary>/// <param name="drive"></param>/// <returns></returns>public static long GetDriveTotalFreeSpace(DriveInfo drive){return drive.TotalFreeSpace;}/// <summary>///     獲取指定磁盤總大小/// </summary>/// <param name="drive"></param>/// <returns></returns>public static long GetDriveTotalSize(DriveInfo drive){return drive.TotalSize;}#region 獲取當前使用的IP,超時時間至少1s /// <summary>///     獲取當前使用的IP,超時時間至少1s/// </summary>/// <returns></returns>public static string GetLocalIP(TimeSpan timeOut, bool isBelieveTimeOutValue = false, bool recordLog = true){if (timeOut < new TimeSpan(0, 0, 1))timeOut = new TimeSpan(0, 0, 1);var isTimeOut = RunApp("route", "print", timeOut, out var result, recordLog);if (isTimeOut && !isBelieveTimeOutValue)try{var tcpClient = new TcpClient();tcpClient.Connect("www.baidu.com", 80);var ip = ((IPEndPoint) tcpClient.Client.LocalEndPoint).Address.ToString();tcpClient.Close();return ip;}catch (Exception exception){Console.WriteLine(exception);return null;}var getMatchedGroup = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");if (getMatchedGroup.Success)return getMatchedGroup.Groups[2].Value;return null;}#endregion#region 獲取本機主DNS/// <summary>///     獲取本機主DNS/// </summary>/// <returns></returns>public static string GetPrimaryDNS(bool recordLog = true){RunApp("nslookup", "", new TimeSpan(0, 0, 1), out var result, recordLog, true); //nslookup會超時var getMatchedGroup = Regex.Match(result, @"\d+\.\d+\.\d+\.\d+");if (getMatchedGroup.Success)return getMatchedGroup.Value;return null;}#endregion/// <summary>///     獲取指定進程最大線程數/// </summary>/// <returns></returns>public static int GetProcessMaxThreadCount(Process process){return process.Threads.Count;}/// <summary>///     獲取指定進程最大線程數/// </summary>/// <returns></returns>public static int GetProcessMaxThreadCount(string processName){var maxThreadCount = -1;foreach (var process in Process.GetProcessesByName(processName))if (maxThreadCount < process.Threads.Count)maxThreadCount = process.Threads.Count;return maxThreadCount;}private static void PrintCategoryAndCounters(PerformanceCounterCategory category,PerformanceCounter[] categoryCounters, bool isPrintTree){Console.WriteLine($@"===============>{category.CategoryName}:[{categoryCounters.Length}]");if (isPrintTree)foreach (var counter in categoryCounters)Console.WriteLine($@"   ""{category.CategoryName}"", ""{counter.CounterName}""");}/// <summary>///     運行一個控制臺程序并返回其輸出參數。耗時至少1s/// </summary>/// <param name="filename">程序名</param>/// <param name="arguments">輸入參數</param>/// <param name="result"></param>/// <param name="recordLog"></param>/// <param name="timeOutTimeSpan"></param>/// <param name="needKill"></param>/// <returns></returns>private static bool RunApp(string filename, string arguments, TimeSpan timeOutTimeSpan, out string result,bool recordLog = true, bool needKill = false){try{var stopwatch = Stopwatch.StartNew();if (recordLog)Console.WriteLine($@"{filename} {arguments}");if (timeOutTimeSpan < new TimeSpan(0, 0, 1))timeOutTimeSpan = new TimeSpan(0, 0, 1);var isTimeOut = false;var process = new Process{StartInfo ={FileName = filename,CreateNoWindow = true,Arguments = arguments,RedirectStandardOutput = true,RedirectStandardInput = true,UseShellExecute = false}};process.Start();using (var streamReader = new StreamReader(process.StandardOutput.BaseStream, Encoding.Default)){if (needKill){Thread.Sleep(200);process.Kill();}while (!process.HasExited)if (stopwatch.Elapsed > timeOutTimeSpan){process.Kill();stopwatch.Stop();isTimeOut = true;break;}result = streamReader.ReadToEnd();streamReader.Close();if (recordLog)Console.WriteLine($@"返回[{result}]耗時:[{stopwatch.Elapsed}]是否超時:{isTimeOut}");return isTimeOut;}}catch (Exception exception){result = exception.ToString();Console.WriteLine($@"出錯[{result}]");return true;}}#endregion#region 獲取本地/遠程所有內存信息/// <summary>///     需要啟動RPC服務,獲取本地內存信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32PhysicalMemoryInfos(PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum eEnum = PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{_LocalManagementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(_LocalManagementScope,new SelectQuery($"SELECT {PhysicalMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PhysicalMemory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PhysicalMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要啟動RPC服務,獲取遠程內存信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32PhysicalMemoryInfos(string remoteHostName,PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum eEnum = PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostName}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {PhysicalMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PhysicalMemory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PhysicalMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要啟動RPC服務,獲取遠程內存信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32PhysicalMemoryInfos(IPAddress remoteHostIp,PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum eEnum = PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostIp}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {PhysicalMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PhysicalMemory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PhysicalMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}#endregion#region 獲取本地/遠程所有原始性能計數器類別信息/// <summary>///     需要啟動RPC服務,獲取本地所有原始性能計數器類別信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>>GetWin32PerfRawDataPerfOsMemoryInfos(PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum eEnum =PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{_LocalManagementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(_LocalManagementScope,new SelectQuery($"SELECT {PerfRawDataPerfOsMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PerfRawData_PerfOS_Memory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PerfRawDataPerfOsMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要啟動RPC服務,獲取遠程所有原始性能計數器類別信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>>GetWin32PerfRawDataPerfOsMemoryInfos(string remoteHostName,PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum eEnum =PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostName}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {PerfRawDataPerfOsMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PerfRawData_PerfOS_Memory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PerfRawDataPerfOsMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要啟動RPC服務,獲取遠程所有原始性能計數器類別信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>>GetWin32PerfRawDataPerfOsMemoryInfos(IPAddress remoteHostIp,PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum eEnum =PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostIp}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {PerfRawDataPerfOsMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PerfRawData_PerfOS_Memory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PerfRawDataPerfOsMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}#endregion#region 獲取本地/遠程所有CPU信息/// <summary>///     需要啟動RPC服務,獲取本地所有 CPU 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32ProcessorInfos(ProcessorInfoEnums.ProcessorInfoEnum eEnum = ProcessorInfoEnums.ProcessorInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{_LocalManagementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(_LocalManagementScope,new SelectQuery($"SELECT {ProcessorInfoEnums.GetQueryString(eEnum)} FROM Win32_Processor")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessorInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要啟動RPC服務,獲取遠程所有 CPU 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32ProcessorInfos(string remoteHostName,ProcessorInfoEnums.ProcessorInfoEnum eEnum = ProcessorInfoEnums.ProcessorInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostName}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {ProcessorInfoEnums.GetQueryString(eEnum)} FROM Win32_Processor")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessorInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要啟動RPC服務,獲取遠程所有 CPU 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32ProcessorInfos(IPAddress remoteHostIp,ProcessorInfoEnums.ProcessorInfoEnum eEnum = ProcessorInfoEnums.ProcessorInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostIp}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {ProcessorInfoEnums.GetQueryString(eEnum)} FROM Win32_Processor")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessorInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}#endregion#region 獲取本地/遠程所有進程信息/// <summary>///     需要啟動RPC服務,獲取本地所有 進程 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32ProcessInfos(string processName = null, ProcessInfoEnums.ProcessInfoEnum eEnum = ProcessInfoEnums.ProcessInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{_LocalManagementScope.Connect();var selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process");if (processName != null)selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process Where Name = '{processName}'");foreach (var managementBaseObject in new ManagementObjectSearcher(_LocalManagementScope,selectQueryString).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要啟動RPC服務,獲取遠程所有 進程 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetRemoteWin32ProcessInfos(string remoteHostName, string processName = null,ProcessInfoEnums.ProcessInfoEnum eEnum = ProcessInfoEnums.ProcessInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostName}\\root\\cimv2");managementScope.Connect();var selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process");if (processName != null)selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process Where Name = '{processName}'");foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,selectQueryString).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要啟動RPC服務,獲取遠程所有 進程 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetRemoteWin32ProcessInfos(IPAddress remoteHostIp, string processName = null,ProcessInfoEnums.ProcessInfoEnum eEnum = ProcessInfoEnums.ProcessInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostIp}\\root\\cimv2");managementScope.Connect();var selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process");if (processName != null)selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process Where Name = '{processName}'");foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,selectQueryString).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}#endregion#region 獲取本地/遠程所有系統信息/// <summary>///     需要啟動RPC服務,獲取本地所有 系統 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32OperatingSystemInfos(OperatingSystemInfoEnums.OperatingSystemInfoEnum eEnum =OperatingSystemInfoEnums.OperatingSystemInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{_LocalManagementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(_LocalManagementScope,new SelectQuery($"SELECT {OperatingSystemInfoEnums.GetQueryString(eEnum)} FROM Win32_OperatingSystem")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{OperatingSystemInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要啟動RPC服務,獲取遠程所有 系統 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32OperatingSystemInfos(string remoteHostName,OperatingSystemInfoEnums.OperatingSystemInfoEnum eEnum =OperatingSystemInfoEnums.OperatingSystemInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostName}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {OperatingSystemInfoEnums.GetQueryString(eEnum)} FROM Win32_OperatingSystem")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{OperatingSystemInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要啟動RPC服務,獲取遠程所有 系統 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32OperatingSystemInfos(IPAddress remoteHostIp,OperatingSystemInfoEnums.OperatingSystemInfoEnum eEnum =OperatingSystemInfoEnums.OperatingSystemInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostIp}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {OperatingSystemInfoEnums.GetQueryString(eEnum)} FROM Win32_OperatingSystem")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{OperatingSystemInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}#endregion#region 單位轉換進制private const int KbDiv = 1024;private const int MbDiv = 1024 * 1024;private const int GbDiv = 1024 * 1024 * 1024;#endregion#region 單個程序Cpu使用大小/// <summary>///     獲取進程一段時間內cpu平均使用率(有誤差),最低500ms 內的平均值/// </summary>/// <returns></returns>public double GetProcessCpuProcessorRatio(Process process, TimeSpan interVal){if (!process.HasExited){var processorTime = new PerformanceCounter("Process", "% Processor Time", process.ProcessName);processorTime.NextValue();if (interVal.TotalMilliseconds < 500)interVal = new TimeSpan(0, 0, 0, 0, 500);Thread.Sleep(interVal);return processorTime.NextValue() / Environment.ProcessorCount;}return 0;}/// <summary>///     獲取進程一段時間內的平均cpu使用率(有誤差),最低500ms 內的平均值/// </summary>/// <returns></returns>public double GetProcessCpuProcessorTime(Process process, TimeSpan interVal){if (!process.HasExited){var prevCpuTime = process.TotalProcessorTime;if (interVal.TotalMilliseconds < 500)interVal = new TimeSpan(0, 0, 0, 0, 500);Thread.Sleep(interVal);var curCpuTime = process.TotalProcessorTime;var value = (curCpuTime - prevCpuTime).TotalMilliseconds / (interVal.TotalMilliseconds - 10) /Environment.ProcessorCount * 100;return value;}return 0;}#endregion#region 單個程序內存使用大小/// <summary>///     獲取關聯進程分配的物理內存量,工作集(進程類)/// </summary>/// <returns></returns>public long GetProcessWorkingSet64Kb(Process process){if (!process.HasExited)return process.WorkingSet64 / KbDiv;return 0;}/// <summary>///     獲取進程分配的物理內存量,公有工作集/// </summary>/// <returns></returns>public float GetProcessWorkingSetKb(Process process){if (!process.HasExited){var processWorkingSet = new PerformanceCounter("Process", "Working Set", process.ProcessName);return processWorkingSet.NextValue() / KbDiv;}return 0;}/// <summary>///     獲取進程分配的物理內存量,私有工作集/// </summary>/// <returns></returns>public float GetProcessWorkingSetPrivateKb(Process process){if (!process.HasExited){var processWorkingSetPrivate =new PerformanceCounter("Process", "Working Set - Private", process.ProcessName);return processWorkingSetPrivate.NextValue() / KbDiv;}return 0;}#endregion#region 系統內存使用大小/// <summary>///     系統內存使用大小Mb/// </summary>/// <returns></returns>public long GetSystemMemoryDosageMb(){return SystemMemoryUsed / MbDiv;}/// <summary>///     系統內存使用大小Gb/// </summary>/// <returns></returns>public long GetSystemMemoryDosageGb(){return SystemMemoryUsed / GbDiv;}#endregion#region AIP聲明[DllImport("IpHlpApi.dll")]public static extern uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);[DllImport("User32")]private static extern int GetWindow(int hWnd, int wCmd);[DllImport("User32")]private static extern int GetWindowLongA(int hWnd, int wIndx);[DllImport("user32.dll")]private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);[DllImport("user32", CharSet = CharSet.Auto)]private static extern int GetWindowTextLength(IntPtr hWnd);#endregion}
}

?

轉載于:https://www.cnblogs.com/Chary/p/No0000112.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/253001.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/253001.shtml
英文地址,請注明出處:http://en.pswp.cn/news/253001.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

I2C總線之(一)---概述

概述&#xff1a;IC 是Inter-Integrated Circuit的縮寫&#xff0c;發音為"eye-squared cee" or "eye-two-cee" , 它是一種兩線接口。 IC 只是用兩條雙向的線&#xff0c;一條 Serial Data Line (SDA) &#xff0c;另一條Serial Clock (SCL)。 SCL&#xf…

js中級(1)

動畫(1) Css樣式提供了運動 過渡的屬性transition 從一種情況到另一種情況叫過渡 Transition:attr time linear delay&#xff1b; Attr 是變化的屬性 Time 是花費的時間 Linear 變化的速度 Delay 是延遲 復習background:url() no-repeat 50% 50% red; Background-image Ba…

I2C總線之(二)---時序

一、協議 1.空閑狀態 I2C總線總線的SDA和SCL兩條信號線同時處于高電平時&#xff0c;規定為總線的空閑狀態。此時各個器件的輸出級場效應管均處在截止狀態&#xff0c;即釋放總線&#xff0c;由兩條信號線各自的上拉電阻把電平拉高。 2.起始位與停止位的定義&#xff1a; 起始信…

微信小程序設置底部導航欄目方法

微信小程序底部想要有一個漂亮的導航欄目&#xff0c;不知道怎么制作&#xff0c;于是百度找到了本篇文章&#xff0c;分享給大家。 好了 小程序的頭部標題 設置好了&#xff0c;我們來說說底部導航欄是如何實現的。 我們先來看個效果圖 這里&#xff0c;我們添加了三個導航圖標…

HTTP協議(3)瀏覽器的使用之查看源碼

在做CTF的Web類題目時&#xff0c;推薦使用Firefox瀏覽器。下面介紹一些在解題過程中關于瀏覽器的常用技巧。首先就是查看源碼。在做Web題目時&#xff0c;經常需要查看網站源碼&#xff0c;有的flag直接就藏在源碼中&#xff0c;有些題目則是在源碼中給出提示和線索&#xff0…

Autofac IoC容器基本使用步驟【1】

原文&#xff1a;http://www.bkjia.com/Asp_Netjc/888119.html 【原文中有一個地方報錯&#xff0c;下面已修改】 一.基本步驟: 1.設計適合控制反轉(IoC)的應用程序 2.給應用程序Autofac 引用. 3.注冊組件. 4.創建一個Container以備后用. 5.從Container創建一個 lifetime scop…

I2C總線之(三)---以C語言理解IIC

為了加深對I2C總線的理解&#xff0c;用C語言模擬IIC總線&#xff0c;邊看源代碼邊讀波形&#xff1a; 如下圖所示的寫操作的時序圖&#xff1a; 讀時序的理解同理。對于時序不理解的朋友請參考“I2C總線之(二)---時序” 完整的程序如下&#xff1a; #include<reg51.h>…

結對編程總結

這個項目我和我的結對伙伴共花了兩個月時間&#xff0c;之所以選這個項目&#xff0c;因為我們之前都學習過Python&#xff0c;也做過類似的程序&#xff0c;相比較其他項目而言&#xff0c;這個項目更合適&#xff0c;也讓我們對詞頻統計方面的知識加深了了解。寫這個程序我們…

JavaScript初學者必看“new”

2019獨角獸企業重金招聘Python工程師標準>>> 譯者按: 本文簡單的介紹了new, 更多的是介紹原型(prototype)&#xff0c;值得一讀。 原文: JavaScript For Beginners: the ‘new’ operator 譯者: Fundebug 為了保證可讀性&#xff0c;本文采用意譯而非直譯。 <di…

libGDX-wiki發布

為方便大家學習和訪問&#xff0c;我將libgdx的wiki爬取到doku-wiki下&#xff0c;專門建立了以下地址。歡迎大家來共同完善。 http://wiki.v5ent.com 轉載于:https://www.cnblogs.com/mignet/p/ligbdx_wiki.html

I2C讀寫時序

1. I2C寫時序圖&#xff1a; 注意&#xff1a;最后一個byte后&#xff0c;結束標志在第十個CLK上升沿之后&#xff1a; 2. I2C讀時序圖&#xff1a; 注意&#xff1a;restart信號格式&#xff1b;讀操作結束前最后一組clk的最后一個上升沿&#xff0c;主機應發送NACK&#xff0…

網站性能優化

基本概念 1、網站吞吐量&#xff1a;TPS/每秒的事務數&#xff0c;QPS/每秒的查詢數&#xff0c;HPS/每秒的HTTP請求數 2、服務器性能指標&#xff1a;系統負載&#xff0c;內存使用&#xff0c;CPU使用&#xff0c;磁盤使用以及網絡I/O等 前端優化方法 1、減少HTTP請求&#x…

JAVA-容器(2)-Collection

&#xff08;基于JDK1.8源碼分析&#xff09; 一&#xff0c;Collection 所有實現Collection接口的類原則上應該提供兩種構造函數&#xff1a; 【1】無參構造-創建一個空的容器 【2】有參構造-創建一個新的Collection&#xff0c;這個新的Collection和傳入的Collection具有相同…

軟件測試工具LoadRunner中如何定義SLA?--轉載

軟件測試工具LoadRunner中如何定義SLA&#xff1f; 瀏覽&#xff1a;2242|更新&#xff1a;2017-04-09 22:50SLA 是您為負載測試場景定義的具體目標。Analysis 將這些目標與軟件測試工具LoadRunner在運行過程中收集和存儲的性能相關數據進行比較&#xff0c;然后確定目標的 SLA…

最近閱讀20171106

java面試題 線上服務內存OOM問題定位三板斧 JVM的GC ROOTS存在于那些地方 mysql innodb怎樣做查詢優化 ----未閱讀 JAVA CAS原理深度分析----未閱讀 轉載于:https://www.cnblogs.com/Tpf386/p/7793248.html

LinuxI2C驅動--從兩個訪問eeprom的例子開始

本小節介紹兩個在linux應用層訪問eeprom的方法&#xff0c;并給出示例代碼方便大家理解。第一個方法是通過sysfs文件系統對eeprom進行訪問&#xff0c;第二個方法是通過eeprom的設備文件進行訪問。這兩個方法分別對應了i2c設備驅動的兩個不同的實現&#xff0c;在后面的小結會詳…

Cookie詳解整理

1.Cookie的誕生 由于HTTP協議是無狀態的&#xff0c;而服務器端的業務必須是要有狀態的。Cookie誕生的最初目的是為了存儲web中的狀態信息&#xff0c;以方便服務器端使用。比如判斷用戶是否是第一次訪問網站。目前最新的規范是RFC 6265&#xff0c;它是一個由瀏覽器服務器共同…

驍龍820和KryoCPU:異構計算與定制計算的作用 【轉】

本文轉載自&#xff1a;https://www.douban.com/group/topic/89037625/ Qualcomm驍龍820處理器專為提供創新用戶體驗的頂級移動終端而設計。為實現消費者所期望的創新&#xff0c;移動處理器必須滿足日益增長的計算需求且降低功耗&#xff0c;同時還要擁有比以往更低的溫度&…

LNMP

準備工作 建立一個軟件包目錄存放 mkdir -p /usr/local/src/ 清理已經安裝包 rpm -e httpd rpm -e mysql rpm -e php yum -y remove httpd yum -y remove mysql yum -y remove php #搜索apache包 rpm -qa http* #強制卸載apache包 rpm -e --nodeps 查詢出來的文件名 #檢查是否卸…