I’m developing a .NET 5 console application and would like to be able to read some basic system info such as CPU temperature, memory usage, CPU usage, etc. My development machine is running windows but the application is deployed to a Linux machine, therefore I’d like to avoid having to write two different sets of code for both OS.
How do I do this in a cross platform way? There are plenty of Windows API and calls that will do this, but I need Linux to work as well.
Advertisement
Answer
There is a github issue open to standardize this as part of the .net runtime. Maybe we’ll see this in .net 6 or 7, who knows… https://github.com/dotnet/runtime/issues/22948
This is one of the better libraries: https://github.com/openhardwaremonitor/openhardwaremonitor. They appear to have attempted some Linux support.
For things like CPU usage you may have success with How to get the CPU Usage in C#? (Windows).
For CPU on Linux, parsing result of command line: https://phoenixnap.com/kb/check-cpu-usage-load-linux. In short:
sudo apt install sysstat mpstat 1
The GC class has methods to get memory used by C# runtime. For system memory, here are a couple resources:
Windows: How do you get total amount of RAM the computer has?
Linux: Run free -m
and parse result using Process
class.
Other links that might be helpful for Linux: