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 Properties private readonly ManagementScope _LocalManagementScope; private readonly PerformanceCounter _pcCpuLoad; //CPU计数器,全局
private const int GwHwndfirst = ;
private const int GwHwndnext = ;
private const int GwlStyle = -;
private const int WsBorder = ;
private const int WsVisible = ; #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 = ;
var managementClassOs = new ManagementClass("Win32_OperatingSystem");
foreach (var managementBaseObject in managementClassOs.GetInstances())
if (managementBaseObject["FreePhysicalMemory"] != null)
availablebytes = * 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.Global
public 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 > )
{
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( * length + );
GetWindowText(hwCurr, sb, sb.Capacity);
var strTitle = sb.ToString();
if (!string.IsNullOrEmpty(strTitle))
apps.Add(strTitle);
}
hwCurr = GetWindow(hwCurr, GwHwndnext);
} return apps;
} #endregion public 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 > )
{
categoryCounters = category.GetCounters(categoryCounterInstanceNames[]);
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 > )
{
categoryCounters = category.GetCounters(categoryCounterInstanceNames[]);
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(, , ))
timeOut = new TimeSpan(, , );
var isTimeOut = RunApp("route", "print", timeOut, out var result, recordLog);
if (isTimeOut && !isBelieveTimeOutValue)
try
{
var tcpClient = new TcpClient();
tcpClient.Connect("www.baidu.com", );
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[].Value;
return null;
} #endregion #region 获取本机主DNS /// <summary>
/// 获取本机主DNS
/// </summary>
/// <returns></returns>
public static string GetPrimaryDNS(bool recordLog = true)
{
RunApp("nslookup", "", new TimeSpan(, , ), 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 = -;
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(, , ))
timeOutTimeSpan = new TimeSpan(, , );
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();
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 = ;
private const int MbDiv = * ;
private const int GbDiv = * * ; #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 < )
interVal = new TimeSpan(, , , , );
Thread.Sleep(interVal);
return processorTime.NextValue() / Environment.ProcessorCount;
}
return ;
} /// <summary>
/// 获取进程一段时间内的平均cpu使用率(有误差),最低500ms 内的平均值
/// </summary>
/// <returns></returns>
public double GetProcessCpuProcessorTime(Process process, TimeSpan interVal)
{
if (!process.HasExited)
{
var prevCpuTime = process.TotalProcessorTime;
if (interVal.TotalMilliseconds < )
interVal = new TimeSpan(, , , , );
Thread.Sleep(interVal);
var curCpuTime = process.TotalProcessorTime;
var value = (curCpuTime - prevCpuTime).TotalMilliseconds / (interVal.TotalMilliseconds - ) /
Environment.ProcessorCount * ;
return value;
}
return ;
} #endregion #region 单个程序内存使用大小 /// <summary>
/// 获取关联进程分配的物理内存量,工作集(进程类)
/// </summary>
/// <returns></returns>
public long GetProcessWorkingSet64Kb(Process process)
{
if (!process.HasExited)
return process.WorkingSet64 / KbDiv;
return ;
} /// <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 ;
} /// <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 ;
} #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
}
}

[No0000112]ComputerInfo,C#获取计算机信息(cpu使用率,内存占用率,硬盘,网络信息)的更多相关文章

  1. wince下的CPU和内存占用率计算

    #include <Windows.h> DWORD Caculation_CPU(LPVOID lpVoid) { MEMORYSTATUS MemoryInfo; DWORD Perc ...

  2. linux ps命令,查看某进程cpu和内存占用率情况, linux ps命令,查看进程cpu和内存占用率排序。 不指定

    背景:有时需要单看某个进程的CPU及占用情况,有时需要看整体进程的一个占用情况.一. linux ps命令,查看某进程cpu和内存占用率情况[root@test vhost]# ps auxUSER  ...

  3. shell脚本采集系统cpu、内存、磁盘、网络信息

    有不少朋友不知道如何用shell脚本采集linux系统相关信息,包括cpu.内存.磁盘.网络等信息,这里脚本小编做下讲解,大家一起来看看吧. 一.cpu信息采集 1),采集cpu使用率采集算法:通过/ ...

  4. linux ps命令,查看进程cpu和内存占用率排序(转)

    使用以下命令查看: ps -aux | sort -k4,4n ps auxw --sort=rss ps auxw --sort=%cpu linux 下的ps命令 %CPU 进程的cpu占用率 % ...

  5. Linux 下用管道执行 ps aux | grep 进程ID 来获取CPU与内存占用率

    #include <stdio.h> #include <unistd.h>   int main() {     char caStdOutLine[1024]; // ps ...

  6. IIS解决CPU和内存占用率过高的问题

    发现进程中的w3wp占用率过高. 经过查询,发现如下: w3wp.exe是在IIS(因特网信息服务器)与应用程序池相关联的一个进程,如果你有多个应用程序池,就会有对应的多个w3wp.exe的进程实例运 ...

  7. 【转载】Linux下查看CPU、内存占用率

    不错的文章(linux系统性能监控--CPU利用率):https://blog.csdn.net/ctthuangcheng/article/details/52795477 在linux的系统维护中 ...

  8. linux系统cpu和内存占用率

    1.top 使用权限:所有使用者 使用方式:top [-] [d delay] [q] [c] [S] [s] [i] [n] [b] 说明:即时显示process的动态 d :改变显示的更新速度,或 ...

  9. 【优化】如何检测移动端 CPU 以及内存占用率

    原文  http://taobaofed.org/blog/2015/12/04/cpu-allocation-profiler/ 前言 6 月底的时候淘宝众筹的 H5 接入到了支付宝钱包,上线前支付 ...

随机推荐

  1. Mysql线程池系列一:什么是线程池和连接池( thread_pool 和 connection_pool)

       thread_pool 和 connection_pool 当客户端请求的数据量比较大的时候,使用线程池可以节约大量的系统资源,使得更多的CPU时间和内存可以高效地利用起来.而数据库连接池的使用 ...

  2. [ci] jenkins kubernetes插件配置(容器模式)-通过jnlp

    有个小伙用sh结合jenkins搞的k8s cicd还不错 jenkins kubernetes插件 首先插件管理,搜索kubernetes plugin安装 配置kubernetes云 配置项目 执 ...

  3. TypeScript学习笔记(九):装饰器(Decorators)

    装饰器简介 装饰器(Decorators)为我们在类的声明及成员上通过元编程语法添加标注提供了一种方式. 需要注意的是:装饰器是一项实验性特性,在未来的版本中可能会发生改变. 若要启用实验性的装饰器特 ...

  4. git合并多个提交

    git合并多个提交 [时间:2016-11] [状态:Open] [关键词:git,git rebase,合并提交,commit] 0. 引言 本文是关于Git提交记录修改的方法,主要是将多个提交记录 ...

  5. 如何取消Visual Studio Browser Link

    VS2013.2015新建MVC网站并浏览后,页面默认自动启用Browser Link功能 解决方法,只需要在web.config中添加配置节点即可 <appSettings> <a ...

  6. 跟Python打包相关的一些文章

    6 things I learned about setuptools Python 101: easy_install or how to create eggs « The Mouse Vs. T ...

  7. 【iCore1S 双核心板_FPGA】例程一:GPIO输出实验——点亮LED

    实验现象: 三色LED循环点亮. 核心源代码: //--------------------Module_LED-----------------------------// module LED( ...

  8. Python 的 Magic Methods 指南(转)

    介绍 本指南是数月博客的总结.主题是魔术方法. 什么是魔术方法呢?它们是面向对象Python语言中的一切.它们是你可以自定义并添加“魔法”到类中的特殊方法.它们被双下划线环绕(比如__init__或_ ...

  9. 什么是对象:EVERYTHING IS OBJECT(万物皆对象)

      所有的事物都有两个方面: 有什么(属性):用来描述对象. 能够做什么(方法):告诉外界对象有那些功能. 后者以前者为基础. 大的对象的属性也可以是一个对象.

  10. DOS、Mac 和 Unix 文件格式+ UltraEdit使用

    文件格式 区分DOS.Mac 和 Unix分别对应三种系统 从文件编码的方式来看,文件可分为ASCII码文件和二进制码文件两种 文件模式 区分ASCII模式和Binary模式  通常由系统决定,大多数 ...