C#获取windows系统资源使用情况

2023-12-27 17:22:45

1.前言

之前有一篇博客介绍如何获取Linux服务器上的资源使用情况《Java 获取服务器资源(内存、负载、磁盘容量)》,这里介绍如何通过C#获取Window系统的资源使用。

2.获取服务器资源

2.1.内存

[DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GlobalMemoryStatusEx(ref MEMORY_INFO mi);

        //定义内存的信息结构
        [StructLayout(LayoutKind.Sequential)]
        private struct MEMORY_INFO {
            public uint DWLength;//当前结构体大小
            public uint DWMemoryLoad;//当前内存使用率
            public ulong ullTotalPhys;//总计物理内存大小
            public ulong ullAvailPhys;//可用物理内存代销
            public ulong ullTotalPagefiles;//总计交换文件大小
            public ulong ullAvailPagefiles;//可用交换文件大小
            public ulong ullTotalVirtual;//总计虚拟内存大小
            public ulong ullAvailVirtual;//可用虚拟内存大小
        }

        private static MEMORY_INFO GetMemoryInfo() {
            MEMORY_INFO memoryInfo = new MEMORY_INFO();
            memoryInfo.DWLength = (uint)System.Runtime.InteropServices.Marshal.SizeOf(memoryInfo);
            GlobalMemoryStatusEx(ref memoryInfo);
            return memoryInfo;
        }

        /// <summary>
        /// 获取内存信息
        /// </summary>
        /// <returns></returns>
        public static ServerMemory GetSysMemoryInfo()
        {
            try
            {
                MEMORY_INFO memoryInfo = GetMemoryInfo();
                ServerMemory serverMemory = new ServerMemory();
                serverMemory.serverId = serverId;
                serverMemory.serverName = serverName;
                serverMemory.memTotal = (uint)(memoryInfo.ullTotalPhys / 1024);
                serverMemory.memFree = (uint)(memoryInfo.ullTotalPagefiles / 1024);
                serverMemory.memAvailable = (uint)(memoryInfo.ullAvailPhys / 1024);
                serverMemory.active = (uint)(memoryInfo.ullAvailPhys/1024);
                long timestamp = CommonUtil.getNowDateTimestamp();
                serverMemory.dateTimestamp = timestamp;
                serverMemory.dateTime = CommonUtil.dateTime2Timestamp(timestamp);
                
                return serverMemory;
            }
            catch (Exception ex) {
                Log.Instance.Error("GetSysMemoryInfo:" + ex.Message);
                return null;
            }
        }

因为获取到的资源是以byte为单位,我这里将其转成了KB,所以除以了1024.

ServerMemory实体类

public class ServerMemory
    {
        public string serverId { set; get; }
        public string serverName { set; get; }
        /// <summary>
        /// 内存总量
        /// </summary>
        public uint memTotal { set; get; }
        /// <summary>
        /// 系统保留量
        /// </summary>
        public uint memFree { set; get; }
        /// <summary>
        /// 应用程序可用量
        /// </summary>
        public uint memAvailable { set; get; }
        /// <summary>
        /// 可使用量
        /// </summary>
        public uint active { set; get; }
        public string dateTime { set; get; }
        public long dateTimestamp { set; get; }
    }

2.2.磁盘

public static ServerDisk GetUsedDisk() {
            try
            {
                List<Dictionary<string, string>> diskInfoList = new List<Dictionary<string, string>>();
                ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
                ManagementObjectCollection disks = diskClass.GetInstances();
                foreach (ManagementObject disk in disks)
                {
                    Dictionary<string, string> diskInfoDic = new Dictionary<string, string>();
                    try
                    {
                        // 磁盘名称
                        diskInfoDic["Name"] = disk["Name"].ToString();
                        // 磁盘描述
                        diskInfoDic["Description"] = disk["Description"].ToString();
                        // 磁盘总容量,可用空间,已用空间
                        if (System.Convert.ToInt64(disk["Size"]) > 0)
                        {
                            long totalSpace = System.Convert.ToInt64(disk["Size"]) / 1024;
                            long freeSpace = System.Convert.ToInt64(disk["FreeSpace"]) / 1024;
                            long usedSpace = totalSpace - freeSpace;
                            diskInfoDic["totalSpace"] = totalSpace.ToString();
                            diskInfoDic["usedSpace"] = usedSpace.ToString();
                            diskInfoDic["freeSpace"] = freeSpace.ToString();
                        }
                        diskInfoList.Add(diskInfoDic);
                    }
                    catch (Exception ex)
                    {
                        Log.Instance.Error("ManagementObject->disk:" + ex.Message);
                    }
                }
                if (diskInfoList.Count > 0)
                {
                    ServerDisk serverDisk = new ServerDisk();
                    serverDisk.serverId = serverId;
                    serverDisk.serverName = serverName;
                    Dictionary<string, DiskInfo> diskMap = new Dictionary<string, DiskInfo>();
                    foreach (Dictionary<string, string> dic in diskInfoList)
                    {
                        if (dic.ContainsKey("totalSpace") && dic.ContainsKey("usedSpace") && dic.ContainsKey("freeSpace"))
                        {
                            DiskInfo diskInfo = new DiskInfo();
                            diskInfo.diskName = dic["Name"];
                            diskInfo.diskSize = double.Parse(dic["totalSpace"]);
                            diskInfo.used = double.Parse(dic["usedSpace"]);
                            diskInfo.avail = double.Parse(dic["freeSpace"]);
                            diskInfo.usageRate = (int)((diskInfo.used / diskInfo.diskSize) * 100);
                            diskMap.Add(diskInfo.diskName, diskInfo);
                        }
                    }
                    serverDisk.diskInfoMap = diskMap;
                    long timestamp = CommonUtil.getNowDateTimestamp();
                    serverDisk.dateTimestamp = timestamp;
                    serverDisk.dateTime = CommonUtil.dateTime2Timestamp(timestamp);
                    return serverDisk;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex) {
                Log.Instance.Error("GetUsedDisk:"+ex.Message);
                return null;
            }
        }

ServerDisk实体类

   public class ServerDisk
    {
        public string serverId { set; get; }
        public string serverName { set; get; }
        public Dictionary<string,DiskInfo> diskInfoMap { set; get; }
        public string dateTime { set; get; }
        public long dateTimestamp { set; get; }
    }

DiskInfo实体类

    public class DiskInfo
    {
        public string diskName { set; get; }
        public double diskSize { set; get; }
        public double used { set; get; }
        public double avail { set; get; }
        public int usageRate { set; get; }
    }

2.3.CPU

public static ServerCpu GetUsedCPU() {
            ManagementClass mc = new ManagementClass("Win32_PerfFormattedData_PerfOs_Processor");
            ManagementObjectCollection moc = mc.GetInstances();
            List <string> list = new List <string> ();
            foreach (ManagementObject mo in moc) {
                if (mo["Name"].ToString() == "_Total") {
                    list.Add(mo["percentprocessorTime"].ToString());
                }
            }
            int percentage = list.Sum(s => int.Parse(s));
            ServerCpu serverCpu = new ServerCpu();
            serverCpu.serverId = serverId;
            serverCpu.serverName = serverName;
            serverCpu.percentage = percentage;
            long timestamp = CommonUtil.getNowDateTimestamp();
            serverCpu.dateTimestamp = timestamp;
            serverCpu.dateTime = CommonUtil.dateTime2Timestamp(timestamp);
            return serverCpu;
        }

ServerCpu实体类

 public class ServerCpu
    {
        public string serverId { set; get; }
        public string serverName { set; get; }
        public int percentage { set; get; }
        public string dateTime { set; get; }
        public long dateTimestamp { set; get; }
    }

3.最终效果

最终我想实现对Linux和Windows服务器的监控,类似效果如下:

文章来源:https://blog.csdn.net/qq_17486399/article/details/135247590
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。