• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c#获取电脑运行状态(cpu,内存,网络,系统运行时间)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 public class DeviceMonitor
    {
        /// <summary>
        ///     % Processor Time 是所有进程线程使用处理器执行指令所花的时间百分比。指令是计算机执行的基础单位。线程是执行指令的对象,进程是程序运行时创建的对象。此计数包括处理某些硬件间隔和陷阱条件所执行的代码。
        /// </summary>
        private static readonly PerformanceCounter CpuCounter =
            new PerformanceCounter("Processor", "% Processor Time", "_Total");


        /// <summary>
        ///     Available MBytes 指能立刻分配给一个进程或系统使用的物理内存数量,以 MB 为单位表示。它等于分配给待机(缓存的)、空闲和零分页列表内存的总和。
        /// </summary>
        private static readonly PerformanceCounter RamCounter = new PerformanceCounter("Memory", "Available MBytes");


        /// <summary>
        ///     System Up Time 指计算机自上次启动后已经运行的时间(以秒计)。此计数器显示启动时间和当前时间之差。
        /// </summary>
        private static readonly PerformanceCounter Uptime = new PerformanceCounter("System", "System Up Time");


        /// <summary>
        ///     开机时间
        /// </summary>
        /// <returns></returns>
        public static TimeSpan GetSystemUpTime()
        {
            Uptime.NextValue();
            var ts = TimeSpan.FromSeconds(Uptime.NextValue());
            return ts;
        }

        /// <summary>
        ///     CPU
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentCpuUsage()
        {
            return CpuCounter.NextValue() + "%";
        }

        /// <summary>
        ///     内存
        /// </summary>
        /// <returns></returns>
        public static string GetAvailableRam()
        {
            return RamCounter.NextValue() + "MB";
        }


        /// <summary>
        ///     线程数
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static int GetThreadCount(string processName)
        {
            var ps = Process.GetProcessesByName(processName).FirstOrDefault();
            if (ps != null)
            {
                return ps.Threads.Count;
            }

            return -1;
        }

        /// <summary>
        ///     程序占用内存
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static string MemoryUsingByApp(string processName)
        {
            var ps = Process.GetProcessesByName(processName).FirstOrDefault();
            if (ps != null)
            {
                return GetDisplayByteSize(ps.WorkingSet64, 3);
            }

            return "--";
        }


        /// <summary>
        ///     所有网络状态
        /// </summary>
        /// <returns></returns>
        public static string GetAllNetworkStatus()
        {
            var allNetStatus = "";
            var allNet = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var i in allNet)
            {
                allNetStatus += " name=" + i.Name + ",type=" + i.NetworkInterfaceType + ",status=" +
                                i.OperationalStatus + "\r\n";
            }

            return allNetStatus;
        }

        /// <summary>
        ///     某程序cpu占用
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static object GetCpuUsageByProcessName(string processName)
        {
            var ct = new PerformanceCounter("Process", "% Processor Time", processName);
            var cpu = ct.NextValue();
            ct.Dispose();
            return cpu;
        }


        /// <summary>
        ///     磁盘控件
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static string GetHddSpace(string processName)
        {
            var ps = Process.GetProcessesByName(processName).FirstOrDefault();
            if (ps == null)
            {
                return "-";
            }

            //var fn = ps.MainModule.FileName;
            var str = "-";
            foreach (var drive in DriveInfo.GetDrives())
            {
                //判断是否是固定磁盘  
                //if (drive.Name == Path.GetPathRoot(fn))
                //{
                str +=
                    $"{drive.Name}可用{GetDisplayByteSize(drive.AvailableFreeSpace)}(总{GetDisplayByteSize(drive.TotalSize)})\r\n";
                //}
            }

            return str;
        }

        /// <summary>
        ///     level=0==G
        ///     level=1==MB
        ///     level=2==Kb
        ///     level=3==B
        /// </summary>
        /// <param name="byteSize"></param>
        /// <param name="stopLevel"></param>
        /// <returns></returns>
        private static string GetDisplayByteSize(long byteSize, int stopLevel = 1)
        {
            if (byteSize >= 1024 * 1024 * 1024)
            {
                var remain = byteSize % (1024 * 1024 * 1024);
                return byteSize / (1024 * 1024 * 1024) + "G " + (stopLevel >= 1 ? GetDisplayByteSize(remain) : "");
            }

            if (byteSize >= 1024 * 1024)
            {
                var remain = byteSize % (1024 * 1024);
                return byteSize / (1024 * 1024) + "M " + (stopLevel >= 2 ? GetDisplayByteSize(remain) : "");
            }

            if (byteSize >= 1024)
            {
                var remain = byteSize % 1024;
                return byteSize / 1024 + "K " + (stopLevel >= 3 ? GetDisplayByteSize(remain) : "");
            }

            if (stopLevel > 3)
            {
                return byteSize + "B ";
            }

            return "";
        }
    }

  

 

显示:

var processName = Process.GetCurrentProcess().ProcessName;

var upTime = DeviceMonitor.GetSystemUpTime();
var cpu = DeviceMonitor.GetCurrentCpuUsage();
var ram = DeviceMonitor.GetAvailableRam();
var net = DeviceMonitor.GetAllNetworkStatus();
var processCpu = DeviceMonitor.GetCpuUsageByProcessName(processName);
var processMem = DeviceMonitor.MemoryUsingByApp(processName);
var threadCt = DeviceMonitor.GetThreadCount(processName);
var hdd = DeviceMonitor.GetHddSpace(processName);
var currentStatus =
$"总CPU占用率={cpu},\r\n" +
$"{processName}占用的CUP={processCpu},\r\n" +
$"空闲可用内存={ram},\r\n" +
$"{processName}占用内存={processMem},\r\n" +
$"{processName}占用线程数={threadCt},\r\n" +
$"开机时间={upTime},\r\n" +
$"网络={net},\r\n" +
$"磁盘={hdd}";
Console.WriteLine(currentStatus);
Console.Read();

 

 

 效果:

 

 

 

 

老版源码地址:https://files.cnblogs.com/files/lizhijian/2021-01-05-%E8%8E%B7%E5%8F%96%E7%94%B5%E8%84%91%E7%8A%B6%E6%80%81.rar

更新2022-04-27-:https://files.cnblogs.com/files/congqiandehoulai/2022-04-27-CSharp%E7%9B%91%E6%8E%A7%E7%94%B5%E8%84%91%E7%8A%B6%E6%80%81.rar


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#和Java的foreach的不同用法发布时间:2022-07-14
下一篇:
C#使用Emit构造拦截器动态代理类发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap