一、获取CPU使用率:

 #region 获取CPU使用率

        #region AIP声明 
        [DllImport("IpHlpApi.dll")]
        extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);         [DllImport("User32")]
        private extern static int GetWindow(int hWnd, int wCmd);         [DllImport("User32")]
        private extern static 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 extern static int GetWindowTextLength(IntPtr hWnd);
        #endregion
        
        public static float? GetCpuUsedRate()
        {
            try
            {
                PerformanceCounter pcCpuLoad;
                pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total")
                {
                    MachineName = "."
                };
                pcCpuLoad.NextValue();
                Thread.Sleep();
                float CpuLoad= pcCpuLoad.NextValue();
                
             return CpuLoad;
            }
            catch
            {
            }
            return ;
        }
        #endregion

二、获取内存使用率

其中ManagementClass类需要手动引用System.Management,然后再using System.Management。

  #region 获取内存使用率
        #region 可用内存         /// <summary>
        ///     获取可用内存
        /// </summary>
        internal static long? GetMemoryAvailable()
        {
           
             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 / MbDiv;
            
        }         #endregion
        internal static double? GetMemoryUsed()
        {
            float? PhysicalMemory = GetPhysicalMemory();
            float? MemoryAvailable = GetMemoryAvailable();
            double? MemoryUsed = (double?)(PhysicalMemory - MemoryAvailable);
            double currentMemoryUsed = (double)MemoryUsed ;
            return currentMemoryUsed ;
        }
        private static long? GetPhysicalMemory()
        {
            //获得物理内存
            var managementClass = new ManagementClass("Win32_ComputerSystem");
            var managementObjectCollection = managementClass.GetInstances();
            long PhysicalMemory;
            foreach (var managementBaseObject in managementObjectCollection)
                if (managementBaseObject["TotalPhysicalMemory"] != null)
                {
                   return long.Parse(managementBaseObject["TotalPhysicalMemory"].ToString())/ MbDiv;
                }
            return null;         }
        public static double? GetMemoryUsedRate()
        {
            float? PhysicalMemory = GetPhysicalMemory();
            float? MemoryAvailable = GetMemoryAvailable();
            double? MemoryUsedRate =(double?)(PhysicalMemory - MemoryAvailable)/ PhysicalMemory;
            return MemoryUsedRate.HasValue ? Convert.ToDouble(MemoryUsedRate * ) : ;
        }
        #endregion         #region 单位转换进制         private const int KbDiv = ;
        private const int MbDiv = * ;
        private const int GbDiv = * * ;         #endregion

三、获取Mac地址

#region 获取当前活动网络MAC地址
        /// <summary>  
        /// 获取本机MAC地址  
        /// </summary>  
        /// <returns>本机MAC地址</returns>  
        public static string GetMacAddress()
        {
            try
            {
                string strMac = string.Empty;
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        strMac = mo["MacAddress"].ToString();
                    }
                }
                moc = null;
                mc = null;
                return strMac;
            }
            catch
            {
                return "unknown";
            }
        }
        #endregion

四、获取磁盘使用率

   #region 获取磁盘占用率
        internal static double GetUsedDiskPercent()
        {
            float? usedSize = GetUsedDiskSize();
            float? totalSize = GetTotalSize();
            double? percent = (double?)usedSize / totalSize;
            return percent.HasValue ? Convert.ToDouble(percent * ) : ;
        }         internal static float? GetUsedDiskSize()
        {
            var currentDrive = GetCurrentDrive();
            float UsedDiskSize =(long)currentDrive?.TotalSize - (long)currentDrive?.TotalFreeSpace;
            return UsedDiskSize / MbDiv;
        }         internal static float? GetTotalSize()
        {
            var currentDrive = GetCurrentDrive();             float TotalSize = (long)currentDrive?.TotalSize / MbDiv;
            return TotalSize;
        }         /// <summary>
        /// 获取当前执行的盘符信息
        /// </summary>
        /// <returns></returns>
        private static DriveInfo GetCurrentDrive()
        {
            string path = Application.StartupPath.ToString().Substring(, );
            return DriveInfo.GetDrives().FirstOrDefault<DriveInfo>(p => p.Name.Equals(path));
        }
        #endregion

C# 获取Windows系统:Cpu使用率,内存使用率,Mac地址,磁盘使用率的更多相关文章

  1. C/C++获取Windows系统CPU和内存及硬盘使用情况

    //1.获取Windows系统内存使用率 //windows 内存 使用率 DWORD getWin_MemUsage(){ MEMORYSTATUS ms; ::GlobalMemoryStatus ...

  2. C/C++获取Linux系统CPU和内存及硬盘使用情况

    需求分析: 不使用Top  df  free 等命令,利用C/C++获取Linux系统CPU和内存及硬盘使用情况 实现: //通过获取/proc/stat (CPU)和/proc/meminfo(内存 ...

  3. Windows系统CPU和内存状态实时查询(Java)

    一.背景 需要查询Windows服务器的CPU和内存状态. Linux系统查询CPU和内存状态很简单,一个top命令搞定,Windows就稍微麻烦一些了. 经过资料查找,发现jdk目前不能直接查询系统 ...

  4. PHP 之获取Windows下CPU、内存的使用率

    <?php /** * Created by PhpStorm. * User: 25754 * Date: 2019/5/4 * Time: 13:42 */ class SystemInfo ...

  5. linux服务器性能——CPU、内存、流量、磁盘使用率的监控

    https://blog.csdn.net/u012859748/article/details/72731080

  6. C#获取特定进程CPU和内存使用率

    首先是获取特定进程对象,可以使用Process.GetProcesses()方法来获取系统中运行的所有进程,或者使用Process.GetCurrentProcess()方法来获取当前程序所对应的进程 ...

  7. Java获取Linux系统cpu使用率

    原文:http://www.open-open.com/code/view/1426152165201 import java.io.BufferedReader; import java.io.Fi ...

  8. php获取linux服务器CPU、内存、硬盘使用率的实现代码

    define("MONITORED_IP", "172.16.0.191"); //被监控的服务器IP地址 也就是本机地址 define("DB_SE ...

  9. Java如何获取系统cpu、内存、硬盘信息

    1 概述 前段时间摸索在Java中怎么获取系统信息包括cpu.内存.硬盘信息等,刚开始使用Java自带的包进行获取,但这样获取的内存信息不够准确并且容易出现找不到相应包等错误,所以后面使用sigar插 ...

  10. Windows系统CPU内存网络性能统计第一篇 内存

    最近翻出以前做过的Windows系统性能统计程序,这个程序可以统计系统中的CPU使用情况,内存使用情况以及网络流量.现在将其整理一下(共有三篇),希望对大家有所帮助. 目录如下: 1.<Wind ...

随机推荐

  1. OAuth2 社区通用组件

    转载:http://www.cyqdata.com/download/article-detail-54302   使用本组件,只需要几行代码,就可以在网站上集成以下效果:     相关文章及使用说明 ...

  2. flask的使用(一)

    1.程序基本的说明 #-*-encoding=utf--*- 从flask中引入类 from flask import Flask ,render_template import config 初始化 ...

  3. UVA 11039 - Building designing 水题哇~

    水题一题,按绝对值排序后扫描一片数组(判断是否异号,我是直接相乘注意中间值越界)即可. 感觉是让我练习sort自定义比较函数的. #include<cstdio> #include< ...

  4. 代码从windows下visual studio到andriod平台迁移的修改记录

    前言 前言也是迁言,从windows的visual studio 2012平台迁移到android平台上,需用修改挺多的代码和需用注意地方. 我们当然的平台当初就考虑了其他平台跨平台的应用问题,所以一 ...

  5. js如何生成[n,m]的随机数

    js如何生成[n,m]的随机数 一.总结 一句话总结:生成随机数就是用的Math的random方法. 1.Math.random()得到的数据的左右开闭情况是怎样的? 左闭又开 所以Math.floo ...

  6. Linux system函数返回值

    例: status = system("./test.sh"); 1.先统一两个说法: (1)system返回值:指调用system函数后的返回值,比如上例中status为syst ...

  7. Lucene学习总结之八:Lucene的查询语法,JavaCC及QueryParser 2014-06-25 14:25 722人阅读 评论(1) 收藏

    一.Lucene的查询语法 Lucene所支持的查询语法可见http://lucene.apache.org/java/3_0_1/queryparsersyntax.html (1) 语法关键字 + ...

  8. php解析xml字符串

    <?php $content = <<<XML <?xml version="1.0" encoding="UTF-8"?> ...

  9. URIEncoding

    http://thoughtfly.iteye.com/blog/1533481 http://docs.spring.io/spring/docs/current/spring-framework- ...

  10. [E2E] Robot Framework introduction

    We will use demo project as an example, go though QuickStart repo. Install: First you should have py ...