首页 > 代码库 > 监控电脑CPU,内存,文件大小,硬盘空间

监控电脑CPU,内存,文件大小,硬盘空间

 public class MonitorTools
    {
        /// <summary>
        /// 获取具体进程的内存,线程等参数情况
        /// </summary>
        /// <param name="processName"></param>
        public static void getWorkingSet(string processName)
        {
            Process[] ps = Process.GetProcesses();
            foreach (Process p in ps)
            {
                if (p.MainWindowHandle != null)
                {
                    if (processName == p.ProcessName)
                    {
                        using (var process = Process.GetProcessesByName(processName)[0])
                        using (var p1 = new PerformanceCounter("Process", "Working Set - Private", processName))
                        using (var p2 = new PerformanceCounter("Process", "Working Set", processName))
                        {
                            Console.WriteLine("{0}{1:N} KB", "工作集(进程类)", process.WorkingSet64 / 1024);
                            Console.WriteLine("{0}{1:N} KB", "内存(专用工作集)", p1.NextValue() / 1024);
                            Console.WriteLine(process.Threads.Count.ToString());//线程
                            Console.WriteLine(process.Id.ToString());//PID
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 遍历获取所有硬盘的可用空间
        /// </summary>
        /// <returns></returns>
        public static string GetDriveInfo()
        {
            string result = string.Empty;
            foreach (DriveInfo item in DriveInfo.GetDrives())
            {
                if (item.DriveType == DriveType.Fixed)
                {
                    result += string.Format("{0} 可用空间{1:N} \r\n", item.Name, item.AvailableFreeSpace / (1024 * 1024) + "MB");
                }
            }
            return result;
        }

        /// <summary>
        /// 根据文件路径获得文件的大小信息
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string GetFileSize(string filePath)
        {
            string length = string.Empty;
            try
            {
                FileInfo file = new FileInfo(filePath);
                if (file != null)
                {
                    length = file.Length.ToString();                    
                }
                return length;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return string.Empty;
            }
        }

        //测试获取CPU,内存等运行情况
        [DllImport("kernel32")]
        public static extern void GetSystemInfo(ref CPU_INFO cpuinfo);
        [DllImport("kernel32")]
        public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo);

        //定义CPU的信息结构
        [StructLayout(LayoutKind.Sequential)]
        public struct CPU_INFO
        {
            public uint dwOemId;
            public uint dwPageSize;
            public uint lpMinimumApplicationAddress;
            public uint lpMaximumApplicationAddress;
            public uint dwActiveProcessorMask;
            public uint dwNumberOfProcessors;
            public uint dwProcessorType;
            public uint dwAllocationGranularity;
            public uint dwProcessorLevel;
            public uint dwProcessorRevision;
        }

        //定义内存的信息结构
        [StructLayout(LayoutKind.Sequential)]
        public struct MEMORY_INFO
        {
            public uint dwLength;
            public uint dwMemoryLoad;
            public uint dwTotalPhys;
            public uint dwAvailPhys;
            public uint dwTotalPageFile;
            public uint dwAvailPageFile;
            public uint dwTotalVirtual;
            public uint dwAvailVirtual;
        }

        /// <summary>
        /// 调用GetSystemInfo函数获取CPU的相关信息
        /// </summary>
        /// <returns></returns>
        public static string GetCPUInfo()
        {
            try
            {
                string CPUresult = string.Empty;
                CPU_INFO CpuInfo;
                CpuInfo = new CPU_INFO();
                GetSystemInfo(ref CpuInfo);
                CPUresult += "本计算机中有" + CpuInfo.dwNumberOfProcessors.ToString() + "个CPU";
                CPUresult += "CPU的类型为" + CpuInfo.dwProcessorType.ToString();
                CPUresult += "CPU等级为" + String.Format("{0:N}", CpuInfo.dwProcessorLevel.ToString());
                CPUresult += "CPU的OEM ID为" + String.Format("{0:N}", CpuInfo.dwOemId.ToString());
                CPUresult += "CPU中的页面大小为" + String.Format("{0:N}", CpuInfo.dwPageSize.ToString());

                return CPUresult;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return string.Empty;
            }
        }

        /// <summary>
        /// 调用GlobalMemoryStatus函数获取内存的相关信息
        /// </summary>
        /// <returns></returns>
        public static string GetMemoryInfo()
        {
            try
            {
                string Memoryresult = string.Empty;
                MEMORY_INFO MemInfo;
                MemInfo = new MEMORY_INFO();
                GlobalMemoryStatus(ref MemInfo);
                Memoryresult += MemInfo.dwMemoryLoad.ToString() + "%的内存正在使用";
                Memoryresult += "物理内存共有" + (MemInfo.dwTotalPhys) / (1024 * 1024) + " MB";
                Memoryresult += "可使用的物理内存有" + (MemInfo.dwAvailPhys) / (1024 * 1024) + " MB";
                Memoryresult += "交换文件总大小为" + (MemInfo.dwTotalPageFile) / (1024 * 1024) + " MB";
                Memoryresult += "尚可交换文件大小为" + (MemInfo.dwAvailPageFile) / (1024 * 1024) + " MB";
                Memoryresult += "总虚拟内存有" + (MemInfo.dwTotalVirtual) / (1024 * 1024) + " MB";
                Memoryresult += "未用虚拟内存有" + (MemInfo.dwAvailVirtual) / (1024 * 1024) + " MB";

                return Memoryresult;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return string.Empty;
            }
        }
    }
 /// <summary>
        /// 根据PID结束指定进程
        /// </summary>
        /// <param name="pid"></param>
        public static bool EndProcess(int pid)
        {
            try
            {
                Process process = Process.GetProcessById(pid);
                process.Kill();
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 监控线程的运行情况,如果退出,则记录退出的错误码和退出时间
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static string MonitorProcess(int pid)
        {
            string Message = string.Empty;
            try
            {
                Process process = Process.GetProcessById(pid);
                if (process.HasExited)
                {
                    Message = string.Format("ExitCode:{0};ExitTime:{1}", process.ExitCode, process.ExitTime.ToString("yyyy年MM月dd HH时mm分ss秒"));
                }
                return Message;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return string.Empty;
            }
        }
        /// <summary>
        /// 调用GetSystemInfo函数获取CPU的相关信息,获取CPU占用率
        /// </summary>
        /// <returns></returns>
        public static string GetCPUInfo()
        {
            string CPUresult = string.Empty;
            try
            {
                PerformanceCounter pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                pcCpuLoad.MachineName = ".";
                pcCpuLoad.NextValue();
                float cpuLoad = pcCpuLoad.NextValue();
                string.Format("CPU占用率:{0} %",cpuLoad);
                return CPUresult;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return string.Empty;
            }
        }