修改日期 | 修改人 | 备注 |
2021-12-20 13:50:02[当前版本] | 孙强 | 1.0 |
2021-12-20 13:49:40 | 孙强 | 1.0 |
最近遇到一个需求就是监测局域网内电脑的CPU,内存,硬盘使用率的项目需求,我查找了相关资料发现在windows平台下通过代码只能监测到自身电脑的相关硬件信息和实时CPU内存使用率等信息。
IP地址
MAC地址
CPU名称
CPU主频
CPU核心
CPU使用率
系统名称
系统架构
内存大小
可用内存大小
内存使用率
硬盘大小
空闲硬盘大小
硬盘用量
using System; using System.Collections.Generic; using System.IO; using System.Management; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; namespace ConsoleApp1 { public class Managementclass { //#region 获得分区信息 ///// ///// 获取分区信息 ///// //public static List<DiskInfo> GetLogicalDrives() //{ // List<DiskInfo> drives = new List<DiskInfo>(); // ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk"); // ManagementObjectCollection disks = diskClass.GetInstances(); // foreach (ManagementObject disk in disks) // { // // DriveType.Fixed 为固定磁盘(硬盘) // if (int.Parse(disk["DriveType"].ToString()) == (int)DriveType.Fixed) // { // drives.Add(new DiskInfo(disk["Name"].ToString(), long.Parse(disk["Size"].ToString()), long.Parse(disk["FreeSpace"].ToString()))); // } // } // return drives; //} ///// ///// 获取特定分区信息 ///// ///// 盘符 //public static List<DiskInfo> GetLogicalDrives(char DriverID) //{ // List<DiskInfo> drives = new List<DiskInfo>(); // WqlObjectQuery wmiquery = new WqlObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DeviceID = ’" + DriverID + ":’"); // ManagementObjectSearcher wmifind = new ManagementObjectSearcher(wmiquery); // foreach (ManagementObject disk in wmifind.Get()) // { // if (int.Parse(disk["DriveType"].ToString()) == (int)DriveType.Fixed) // { // drives.Add(new DiskInfo(disk["Name"].ToString(), long.Parse(disk["Size"].ToString()), long.Parse(disk["FreeSpace"].ToString()))); // } // } // return drives; //} //#endregion /// <summary> /// 查找cpu的名称,主频, 核心数 /// </summary> /// <returns></returns> public static Tuple<string, string> GetCPU() { Tuple<string, string> result = null; try { ManagementClass mcCPU = new ManagementClass("Win32_Processor"); ManagementObjectCollection mocCPU = mcCPU.GetInstances(); foreach (ManagementObject m in mocCPU) { string name = m["Name"].ToString(); string[] parts = name.Split('@'); result = new Tuple<string, string>(parts[0].Split('-')[0] + "处理器", parts[1]); break; } } catch { } return result; } /// <summary> /// 获取cpu核心数 /// </summary> /// <returns></returns> public static string GetCPU_Count() { string str = ""; try { int coreCount = 0; foreach (var item in new ManagementObjectSearcher("Select * from Win32_Processor").Get()) { coreCount += int.Parse(item["NumberOfCores"].ToString()); } if (coreCount == 2) { return "2核"; } str = coreCount.ToString() + "核"; } catch { } return str; } //获得物理总内存 public static string get_TotalPhysicalMemory() { try { long nResult = 0; ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { long.TryParse(mo["TotalPhysicalMemory"].ToString(), out nResult); } moc = null; mc = null; string temp=Math.Round((decimal)nResult / 1024 / 1024 / 1024).ToString(); return temp; } catch { return ""; } } /// <summary> /// 获取系统内存大小 /// </summary> /// <returns>内存大小(单位M)</returns> public static string GetPhisicalMemory() { ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象 searcher.Query = new SelectQuery(WindowsAPIType.Win32_PhysicalMemory.ToString(), "", new string[] { WindowsAPIKeys.Capacity.ToString() });//设置查询条件 ManagementObjectCollection collection = searcher.Get(); //获取内存容量 ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator(); long capacity = 0; while (em.MoveNext()) { ManagementBaseObject baseObj = em.Current; if (baseObj.Properties[WindowsAPIKeys.Capacity.ToString()].Value != null) { try { capacity += long.Parse(baseObj.Properties[WindowsAPIKeys.Capacity.ToString()].Value.ToString()); } catch { return ""; } } } return ToGB((double)capacity, 1024.0); } #region 可用内存 /// /// 获取可用内存 /// public static string Get_MemoryAvailable() { string availableMemory = ""; ManagementClass mos = new ManagementClass("Win32_OperatingSystem"); foreach (ManagementObject mo in mos.GetInstances()) { if (mo["FreePhysicalMemory"] != null) { //availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString()); availableMemory = (Convert.ToDouble(mo["FreePhysicalMemory"]) / 1024 / 1024).ToString("0.00"); } } return availableMemory; } #endregion /// <summary> /// 将字节转换为GB /// </summary> /// <param name="size">字节值</param> /// <param name="mod">除数,硬盘除以1000,内存除以1024</param> /// <returns></returns> public static string ToGB(double size, double mod) { String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB" }; int i = 0; while (size >= mod) { size /= mod; i++; } return Math.Round(size) + units[i]; } public static Tuple<string, string> GetDisk() { DriveInfo[] drives = DriveInfo.GetDrives(); long totalFreeSpace = 0; long totalDiskSize = 0; foreach (var drive in drives) { if (drive.IsReady) //判断代码运行时 磁盘是可操作作态 { totalFreeSpace += drive.AvailableFreeSpace; totalDiskSize += drive.TotalSize; } } string item1=((decimal)totalDiskSize / 1024 / 1024 / 1024).ToString("0.00"); string item2 = ((decimal)totalFreeSpace / 1024 / 1024 / 1024).ToString("0.00"); return new Tuple<string, string>(item1, item2); //Console.WriteLine(string.Format("硬盘总容量: {0} 剩余: {1}", totalDiskSize / 1024 / 1024 / 1024 + "GB", totalFreeSpace / 1024 / 1024 / 1024 + "GB")); } //获取mac地址 public static string get_mac_address() { string mac = ""; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { mac = mo["MacAddress"].ToString(); } mo.Dispose(); } return mac; } //获取本机的ip地址 public static List<string> get_ip() { List<string> list = new List<string>(); string name = Dns.GetHostName(); IPAddress[] ipadrlist = Dns.GetHostAddresses(name); foreach (IPAddress ipa in ipadrlist) { if (ipa.AddressFamily == AddressFamily.InterNetwork) list.Add(ipa.ToString()); //Console.WriteLine(ipa.ToString()); } return list; } } } /// <summary> /// windows api 名称 /// </summary> public enum WindowsAPIType { /// <summary> /// 内存 /// </summary> Win32_PhysicalMemory, /// <summary> /// cpu /// </summary> Win32_Processor, /// <summary> /// 硬盘 /// </summary> win32_DiskDrive, /// <summary> /// 电脑型号 /// </summary> Win32_ComputerSystemProduct, /// <summary> /// 分辨率 /// </summary> Win32_DesktopMonitor, /// <summary> /// 显卡 /// </summary> Win32_VideoController, /// <summary> /// 操作系统 /// </summary> Win32_OperatingSystem } public enum WindowsAPIKeys { /// <summary> /// 名称 /// </summary> Name, /// <summary> /// 显卡芯片 /// </summary> VideoProcessor, /// <summary> /// 显存大小 /// </summary> AdapterRAM, /// <summary> /// 分辨率宽 /// </summary> ScreenWidth, /// <summary> /// 分辨率高 /// </summary> ScreenHeight, /// <summary> /// 电脑型号 /// </summary> Version, /// <summary> /// 硬盘容量 /// </summary> Size, /// <summary> /// 内存容量 /// </summary> Capacity, /// <summary> /// cpu核心数 /// </summary> NumberOfCores }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApp1 { /// <summary> /// 性能计数器 /// </summary> public class PerformanceCounterClass { /// <summary> /// 获取性能计数器类别列表 /// </summary> public static string GetCategoryNameList() { string strReturn = "CategoryName: \r\n"; PerformanceCounterCategory[] myCat2; myCat2 = PerformanceCounterCategory.GetCategories(); for (int i = 0; i < myCat2.Length; i++) { strReturn += myCat2[i].CategoryName.ToString()+ " ; CounterHelp:" + myCat2[i].CategoryHelp + "\r\n"; } return strReturn; } /// <summary> /// 获取性能计数器类别下的实例的名称实例下的性能计数器的名称 /// </summary> /// <param name="CategoryName"></param> public static string GetInstanceNameListANDCounterNameList(string CategoryName) { string strReturn = ""; string[] instanceNames; ArrayList counters = new ArrayList(); PerformanceCounterCategory mycat = new PerformanceCounterCategory(CategoryName); try { instanceNames = mycat.GetInstanceNames(); if (instanceNames.Length == 0) { counters.AddRange(mycat.GetCounters()); } else { for (int i = 0; i < instanceNames.Length; i++) { strReturn += "instanceNames:"+ instanceNames[i] + ";【\r\n"; foreach(var item in mycat.GetCounters(instanceNames[i])) { strReturn += "CounterName: "+ item.CounterName+ " ; CounterHelp: " + item.CounterHelp+ "\r\n"; } strReturn += "】\r\n"; //counters.AddRange(mycat.GetCounters(instanceNames[i])); } } for (int i = 0; i < instanceNames.Length; i++) { //strReturn += instanceNames[i] + ";"; } foreach (PerformanceCounter counter in counters) { strReturn += "instanceNames:空空的字符;【"; strReturn += "CounterName: " + counter.CounterName + " ; CounterHelp: " + counter.CounterHelp; strReturn += "】\r\n"; //strReturn += counter.CounterName + ";"; } } catch (Exception) { throw new Exception("Unable to list the counters for this category"); } return strReturn; } /// <summary> /// 根据categoryName,counterName,instanceName获得性能情况显示 /// </summary> /// <param name="CategoryName"></param> /// <param name="InstanceName"></param> /// <param name="CounterName"></param> public static float PerformanceCounterFun(string CategoryName, string CounterName, string InstanceName) { PerformanceCounter pc = new PerformanceCounter(CategoryName, CounterName, InstanceName); pc.NextValue(); Thread.Sleep(1000); return pc.NextValue(); } } }
Configure data = new Configure(); data.IP = Managementclass.get_ip(); data.MAC = Managementclass.get_mac_address(); Tuple<string, string> cpuinfo = Managementclass.GetCPU(); data.CPUName = cpuinfo.Item1; data.CPUClockSpeed = cpuinfo.Item2; data.CPUCore = Managementclass.GetCPU_Count(); data.CPUUsage = string.Format("{0:0.0}", PerformanceCounterClass.PerformanceCounterFun("Processor", "% Processor Time", "_Total")) + "%"; var memorySize = Managementclass.get_TotalPhysicalMemory(); data.MemorySize = memorySize + "GB"; var memoryFreeSize = Managementclass.Get_MemoryAvailable(); data.MemoryFreeSize = memoryFreeSize + "GB"; data.MemoryUsage = string.Format("{0:0.0%}", (Convert.ToDecimal(memorySize) - Convert.ToDecimal(memoryFreeSize)) / Convert.ToDecimal(memorySize)); Tuple<string, string> diskinfo = Managementclass.GetDisk(); data.DiskSize = diskinfo.Item1 + "GB"; data.DiskFreeSize = diskinfo.Item2 + "GB"; data.DiskUsage = string.Format("{0:0.0%}", (Convert.ToDecimal(diskinfo.Item1) - Convert.ToDecimal(diskinfo.Item2)) / Convert.ToDecimal(diskinfo.Item1)); data.SystemName = RuntimeInformation.OSDescription; data.SystemArchitecture = RuntimeInformation.OSArchitecture.ToString();