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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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

posted @   灰主流  阅读(3626)  评论(5编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示