get system cpu temperature in fahrenheit in csharp

You can get the system CPU temperature in Fahrenheit using the following code in C# on a Windows machine:

main.cs
using System.Management;

public float GetCpuTemperature()
{
    float temp = 0;

    // Create a new ManagementObjectSearcher object
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature");

    // Get the ManagementObjectCollection object
    ManagementObjectCollection moc = searcher.Get();

    foreach (ManagementObject mo in moc)
    {
        // Get the temperature value
        temp = Convert.ToSingle(mo["CurrentTemperature"].ToString());

        // Convert the temperature to Fahrenheit
        temp = ((temp - 2732) / 10) * 1.8 + 32;
    }

    return temp;
}
646 chars
24 lines

In the above code, we are using the ManagementObjectSearcher class to query the WMI (Windows Management Instrumentation) repository to get the current CPU temperature. The temperature value returned by WMI is in Kelvin, so we convert it to Fahrenheit using the formula (K - 273.15) * 1.8 + 32.

Note: The ManagementObjectSearcher class requires administrative privileges to access the WMI repository.

gistlibby LogSnag