By yeyeyerman


2009-07-28 16:03:50 8 Comments

I need to gather some system's information for the application I'm developing. The memory available and the CPU load are easy to get using C#. Unfortunately, the CPU temperature it's not that easy. I have tried using WMI but I couldn't get anything using

Win32_TemperatureProbe

or

MSAcpi_ThermalZoneTemperature

Has anybody already dealt with this issue? I'm wondering how monitoring programs, as SiSoftware Sandra, can get that information...

Just in case anybody is interested, here is the code of the class:

public class SystemInformation
{
    private System.Diagnostics.PerformanceCounter m_memoryCounter;
    private System.Diagnostics.PerformanceCounter m_CPUCounter;

    public SystemInformation()
    {
        m_memoryCounter = new System.Diagnostics.PerformanceCounter();
        m_memoryCounter.CategoryName = "Memory";
        m_memoryCounter.CounterName = "Available MBytes";

        m_CPUCounter = new System.Diagnostics.PerformanceCounter();
        m_CPUCounter.CategoryName = "Processor";
        m_CPUCounter.CounterName = "% Processor Time";
        m_CPUCounter.InstanceName = "_Total"; 
    }

    public float GetAvailableMemory()
    {
        return m_memoryCounter.NextValue();
    }

    public float GetCPULoad()
    {
        return m_CPUCounter.NextValue();
    }

    public float GetCPUTemperature()
    {
        //...
        return 0;
    }
}

8 comments

@Ali Zahid 2018-08-08 06:56:54

You can give the Open Hardware Monitor a go, although it lacks support for the latest processors.

internal sealed class CpuTemperatureReader : IDisposable
{
    private readonly Computer _computer;

    public CpuTemperatureReader()
    {
        _computer = new Computer { CPUEnabled = true };
        _computer.Open();
    }

    public IReadOnlyDictionary<string, float> GetTemperaturesInCelsius()
    {
        var coreAndTemperature = new Dictionary<string, float>();

        foreach (var hardware in _computer.Hardware)
        {
            hardware.Update(); //use hardware.Name to get CPU model
            foreach (var sensor in hardware.Sensors)
            {
                if (sensor.SensorType == SensorType.Temperature && sensor.Value.HasValue)
                    coreAndTemperature.Add(sensor.Name, sensor.Value.Value);
            }
        }

        return coreAndTemperature;
    }

    public void Dispose()
    {
        try
        {
            _computer.Close();
        }
        catch (Exception)
        {
            //ignore closing errors
        }
    }
}

Download the zip from the official source, extract and add a reference to OpenHardwareMonitorLib.dll in your project.

@TheQult 2018-06-05 10:40:15

I extracted the CPU part from Open Hardware Monitor into a separated library, exposing sensors and members normally hidden into OHM. It also includes many updates (like the support for Ryzen and Xeon) because on OHM they don't accept pull requests since 2015.

https://www.nuget.org/packages/HardwareProviders.CPU.Standard/

Let know your opinion :)

@Aousaf rashid 2018-06-05 20:56:47

where are it's docs ? how should i use it ?

@TheQult 2018-06-07 06:17:57

On the project site displayed on the page :) github.com/matteofabbri/HardwareProviders

@Wobbles 2019-06-13 12:34:26

unfortunately this lib has a lot of compatibility issues, for instance on a i7-9700k which has no HT, it throws an exception when trying to discover CPU's

@haoming weng 2018-02-02 02:54:00

It's depends on if your computer support WMI. My computer can't run this WMI demo too.

But I successfully get the CPU temperature via Open Hardware Monitor. Add the Openhardwaremonitor reference in Visual Studio. It's easier. Try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor.Hardware;
namespace Get_CPU_Temp5
{
   class Program
   {
       public class UpdateVisitor : IVisitor
       {
           public void VisitComputer(IComputer computer)
           {
               computer.Traverse(this);
           }
           public void VisitHardware(IHardware hardware)
           {
               hardware.Update();
               foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
           }
           public void VisitSensor(ISensor sensor) { }
           public void VisitParameter(IParameter parameter) { }
       }
       static void GetSystemInfo()
       {
           UpdateVisitor updateVisitor = new UpdateVisitor();
           Computer computer = new Computer();
           computer.Open();
           computer.CPUEnabled = true;
           computer.Accept(updateVisitor);
           for (int i = 0; i < computer.Hardware.Length; i++)
           {
               if (computer.Hardware[i].HardwareType == HardwareType.CPU)
               {
                   for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
                   {
                       if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
                               Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
                   }
               }
           }
           computer.Close();
       }
       static void Main(string[] args)
       {
           while (true)
           {
               GetSystemInfo();
           }
       }
   }
}

You need to run this demo as administrator.

You can see the tutorial here: http://www.lattepanda.com/topic-f11t3004.html

@Jens 2012-03-05 10:10:56

For others who may come by here, maybe take a look at : http://openhardwaremonitor.org/

Follow that link and at first you might think, "hey that's an Application, that is why it was removed, the question was how to do this from C# code, not to find an application that can tell me the temperature..." This is where it shows you are not willing to invest enough time in reading what "Open Hardware Monitor" also is.

They also include a Data Interface, here is the description:

Data Interface The Open Hardware Monitor publishes all sensor data to WMI (Windows Management Instrumentation). This allows other applications to read and use the sensor information as well. A preliminary documentation of the interface can be found here(click).

When you download it, it contains the OpenHardwareMonitor.exe application, you're not looking for that one. It also contains the OpenHardwareMonitorLib.dll, you're looking for that one.

It is mostly, if not 100%, just a wrapper around the WinRing0 API, which you could choose to wrap your self if you feel like it.

I have tried this out from a C# app myself, and it works. Although it is still in beta, it seemed rather stable. It is also open source so it could be a good starting point instead.

At the end of the day I find it hard to believe that is not on topic of this question.

@CJxD 2012-03-24 10:41:16

Can you link any documentation about usage of the OpenHardware Lib? I can't seem to find out how to use this in my project.

@Jens 2012-03-26 11:02:00

Unfortunetly not, I used plain old "discovery" to find the things I needed... But what do you have problems with?... At it's very basic it is instantiating the "Computer" class and then just work on from there... (e.g. Computer -> IHardware -> ISensors) Alternatively download the source from their SVN repository and try to figure their own GUI out, personally I didn't have that big of an issue to just discover things, but if your missing something specific it could maybe be?

@Jens 2012-03-26 11:10:43

And with figuring out their GUI, i mean as a source for inspiration to how you get access the the various different sensors and so on... And then replicate that usage in your own project.

@Ivan Peric 2014-01-17 17:39:18

This really helped. Found here much more than I was even looking for. Thank you.

@Lasse Rasch 2010-06-24 22:06:31

I know this post is old, but just wanted to add a comment if somebody should be looking at this post and trying to find a solution for this problem.

You can indeed read the CPU temperature very easily in C# by using a WMI approach.

To get a Celsius value, I have created a wrapper that converts the value returned by WMI and wraps it into an easy to use object.

Please remember to add a reference to the System.Management.dll in Visual Studio.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace RCoding.Common.Diagnostics.SystemInfo
{
    public class Temperature
    {
        public double CurrentValue { get; set; }
        public string InstanceName { get; set; }
        public static List<Temperature> Temperatures
        {
            get
            {
                List<Temperature> result = new List<Temperature>();
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature");
                foreach (ManagementObject obj in searcher.Get())
                {
                    Double temp = Convert.ToDouble(obj["CurrentTemperature"].ToString());
                    temp = (temp - 2732) / 10.0;
                    result.Add(new Temperature { CurrentValue = temp, InstanceName = obj["InstanceName"].ToString() });
                }
                return result;

            }
        }
    }
}

Update 25.06.2010:

(Just saw that a link was posted to the same kind of solution above... Anyway, I will leave this piece of code if somebody should want to use it :-) )

@Thomas Levesque 2011-07-20 16:16:37

Did you read the question? The OP said he already tried MSAcpi_ThermalZoneTemperature...

@zezba9000 2017-09-06 22:15:23

This isn't the CPU temperature, I think its case temperature. You can check using CPUID.

@samoz 2009-07-28 16:11:50

I'm pretty sure it's manufacturer dependent, since they will be accessed through an I/O port. If you have a specific board you're trying to work with, try looking through the manuals and/or contacting the manufacturer.

If you want to do this for a lot of different boards, I'd recommend contacting someone at something like SiSoftware or be prepared to read a LOT of motherboard manuals.

As another note, not all boards have temperature monitors.

You also might run into problems getting privileged access from the kernel.

@Jet 2013-03-09 08:41:11

It can be done in your code via WMI. I've found a tool from Microsoft that creates code for it.

The WMI Code Creator tool allows you to generate VBScript, C#, and VB .NET code that uses WMI to complete a management task such as querying for management data, executing a method from a WMI class, or receiving event notifications using WMI.

You can download it here.

@Jon Grant 2009-07-28 16:13:38

There is a blog post with some C# sample code on how to do it here.

@ewanm89 2009-07-28 16:15:35

That still requires that the vendor's driver is exposing it via WMI.

Related Questions

Sponsored Content

39 Answered Questions

42 Answered Questions

[SOLVED] How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

  • 2008-09-29 22:30:28
  • mistrmark
  • 1044476 View
  • 1799 Score
  • 42 Answer
  • Tags:   c# .net excel file-io

26 Answered Questions

[SOLVED] How can I get the application's path in a .NET console application?

27 Answered Questions

[SOLVED] How to enumerate an enum?

28 Answered Questions

[SOLVED] Get int value from enum in C#

  • 2009-06-03 06:46:39
  • jim
  • 1407609 View
  • 1687 Score
  • 28 Answer
  • Tags:   c# enums casting int

31 Answered Questions

[SOLVED] What is a NullReferenceException, and how do I fix it?

61 Answered Questions

[SOLVED] How do I calculate someone's age in C#?

  • 2008-07-31 23:40:59
  • Jeff Atwood
  • 571655 View
  • 1742 Score
  • 61 Answer
  • Tags:   c# .net datetime

47 Answered Questions

[SOLVED] How do I update the GUI from another thread?

8 Answered Questions

[SOLVED] How to loop through all enum values in C#?

Sponsored Content