get system cpu temperature in celsius in csharp

We can get the system CPU temperature by using the ManagementObjectSearcher class in the System.Management namespace. Here's an example code snippet that gets the temperature in Celsius:

main.cs
using System.Management;

public static float GetCpuTemperature()
{
    float cpuTemperature = 0;

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature");

    foreach (ManagementObject obj in searcher.Get())
    {
        double temperature = Convert.ToDouble(obj["CurrentTemperature"].ToString()) - 2732.5;
        cpuTemperature = (float)Math.Round(temperature / 10.0, 2);
    }

    return cpuTemperature;
}
486 chars
17 lines

This code queries the MSAcpi_ThermalZoneTemperature class in the root\WMI namespace to get the current CPU temperature. The temperature is returned in tenths of a Kelvin, so we need to subtract 2732.5 and then divide by 10 to get the Celsius temperature. Finally, the temperature is rounded to 2 decimal places and returned as a float.

gistlibby LogSnag